HTML and JS form

0

Some bug in the code ???

  

Error Uncaught TypeError: Can not read property 'value' of null

HTML

<form>

        <label for="nombre">Nombre: </label>
        <input type="text" name="nombre" id="nombre" />


        <label for="edad">Edad </label>
        <input type="number" name="edad" id="edad" />

        <input type="button" name="name" id="enviar" value="Enviar" />


    </form>

JS

function camposLlenos() {
    var llenos;

    if ((document.getElementById("nombre").value!=="") && (document.getElementById("edad").value!=="")) {
        llenos = true;
    } else {
        llenos = false;
    }

}
    
asked by Bender 04.12.2017 в 20:39
source

1 answer

2

To restrict the sending of your form you could use the event onsubmit which is applied to the same form, this event will trigger a function that will return true if the condition is met (send data) or false if it is not met (visual message to the user).

Your form lacked the attributes method which is the method by which the data is sent and action which is the path of the php file that will process the data sent .

function camposLlenos() {
    if ((document.getElementById("nombre").value!=="") && (document.getElementById("edad").value!=="")) {
      return true;
    } else {
      alert('Por favor llene todos los campos');
      return false;
    }

}
<form onsubmit="return camposLlenos()" action="#" method="post">
  <label for="nombre">Nombre: </label>
  <input type="text" name="nombre" id="nombre" />

  <label for="edad">Edad </label>
  <input type="number" name="edad" id="edad" />

  <input type="submit" name="name" id="enviar" value="Enviar" />
</form>
    
answered by 04.12.2017 в 21:08