Check full fields jquery

3

I am trying to do a 2 input text check and when the keyup is executed, even if only the input name is filled, it enters the else and the IF is not fulfilled.

JS

$( document ).ready(function() {

  $("#formulario input").keyup(function() {

      $NombreText = $("#name").val();
      $ApellidosText= $("#surname").val();

      if( $NombreText.length<=0 && $ApellidosText.length<= 0){

        console.log("vacio")
      }
      else{
        console.log("lleno")
      } 
   });
});

HTML

<form id="formulario" action="">

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

    <label for="">Apellidos</label>
    <input type="text" id="surname">

    <button>ENVIAR</button>

</form>

    
asked by Daniel Moreno Martin 01.10.2018 в 17:09
source

2 answers

2

Just change the if loggia change && to || :

$( document ).ready(function() {

  $("#formulario input").keyup(function() {

      $NombreText = $("#name").val();
      $ApellidosText= $("#surname").val();

      if( $NombreText.length<=0 || $ApellidosText.length<= 0){

        console.log("vacio")
      }
      else{
        console.log("lleno")
      } 
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="formulario" action="">

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

    <label for="">Apellidos</label>
    <input type="text" id="surname">

    <button>ENVIAR</button>

</form>

I hope it's the answer to your problem.

    
answered by 01.10.2018 / 17:12
source
0

You could write it in a shorter way like this:

    $( document ).ready(function() {
      $("#formulario input").keyup(function() {
        console.log( !$("#name").val() && !$("#surname").val() ? 'vacio' : 'lleno');
   });
});
    
answered by 02.10.2018 в 00:28