Change title by Js

1

Good, my goal is that when entering a text in the input, the paragraph whose id is "my title", change by the text entered in that input. Surely e is that the Js code is not right.

HTML

<html>
<head>
  <script src="DH16.js"></script>
  <link rel="StyleSheet" href="DH16.css" type="text/css">
</head>
<body id="cuerpo">
  <header>
    <h1 id="titulo">
      Editor de Titulos
    </h1>
  </header>
  <p id="principal">
    Mi titulo
  </p>
   <br>
   <br>
   <div id="todo">
     Titulo:
     <input type="text" id="newtitulo">
     <input type="button" value="Cambiar titulo" onclick="cambiarTitulo()">
   </div>
  </body>
 </html>

JavaScript

  function cambiarTitulo() {
var titulo=document.getElementById('newtitulo');
var principal=document.getElementById('principal');
principal=titulo;
}

CSS

#principal {
  font-size:15px;
  border:1px solid #000000;
  background-color: #ffff00;
}

#titulo {
  text-align: center;
  font-size: 45px;
  color: #D7DBDD;
  font-family: "PCBius";
  padding:15px;
  margin:15px;
}

#cuerpo{
  background-image: url('negro.jpg');
}

#todo{
  color: white;
  font-size:18px;
}
    
asked by Vendetta 09.08.2017 в 10:36
source

1 answer

4

That's right, your JS code is not correct, the correct way would be:

function cambiarTitulo() {

//Obtenemos el valor del input
var titulo=document.getElementById('newtitulo').value; <-- Notese el .value

//Aplicamos el valor de la variable titulo
document.getElementById('principal').innerHTML=titulo;

}

And if you want it cooler:

Put an onKeyUp event on the input

......
<div id="todo">
     Titulo:
     <input type="text" id="newtitulo" onKeyUp="javascript:dataBinding(this)">
     <!--<input type="button" value="Cambiar titulo" onclick="cambiarTitulo()">-->
   </div>
......

function dataBinding(elem){
  //Obtenemos el valor del input
  var titulo=elem.value; 

  //Aplicamos el valor de la variable titulo
  document.getElementById('principal').innerHTML=titulo;
}

Here the jsfiddle

    
answered by 09.08.2017 / 10:42
source