Take input values in JavaScript forms

0

I can not see the results that I write in the fields of the form, I'm doing it in the following way but I do not get so much what I entered in the user field or in the password field.

function contrasena() {

  //HTML

  document.getElementById("cuerpoCentral").innerHTML =

    '<form id="formLogin">' +
    "Usuario:" + '<br>' +
    '<input id="user" type="text" name="username">' + '<br>' + '<br>' + 'Contraseña:' + '<br>' +
    '<input id="pass" type="password" name="pass">' + '<br>' +
    '</form>' + '<br>' +
    '<button onclick="contrasena()">' + 'Comprobar' + '</button>';

  //JS

  var myInput = document.getElementById("user");
  var myInput2 = document.getElementById("pass");

  alert(myInput.value);
  alert(myInput2.value);

  alert(myInput.value.length);
  alert(myInput2.value.length);
}
<html>

<head>
  <script src="contrasena.js"></script>

</head>

<body>
  <div id="cuerpoCentral">
  </div>
</body>

</html>
    
asked by InThaHouse 26.11.2018 в 17:44
source

1 answer

1

You need to extract the innerHtml of your function so that the form containing the button is created first and then when you click the button, the function can be executed, something like this:

<html>

<head>


</head>

<body>
  <div id="cuerpoCentral">
  </div>
</body>
<script>
 document.getElementById("cuerpoCentral").innerHTML =

    '<form id="formLogin">' +
    "Usuario:" + '<br>' +
    '<input id="user" type="text" name="username">' + '<br>' + '<br>' + 'Contraseña:' + '<br>' +
    '<input id="pass" type="password" name="pass">' + '<br>' +
    '</form>' + '<br>' +
    '<button onclick="contrasena()">' + 'Comprobar' + '</button>';
    
    function contrasena() {

  var myInput = document.getElementById("user");
  var myInput2 = document.getElementById("pass");

  alert(myInput.value);
  alert(myInput2.value);

  alert(myInput.value.length);
  alert(myInput2.value.length);
}
</script>
</html>

Also you need to put your javascript at the end of your html to finish loading everything, and so detect the div and create the form based on it.

    
answered by 26.11.2018 / 18:11
source