How to get the value of several filled fields using jQuery?

4

I currently have a customer search system that can be searched by cpf, cnpj, phone, address, email and various other information, I can search a customer asking if there is a customer having an email and a phone, my question and the following, I use a tablist that has a form and in this form I can get only the first field filled and not all, in case I need to get all the fields that are filled, eg: p>

<form  id='form_pesquisa'>
   <label for='nome'>Nome</label>
   <input type='text' name='nome' id='nome'/>
   <label for='email'>Email</label>
   <input type='text' name='email' id='email'/>
</form>

$("#nome,#email").change(function(){
  var search = $('#form_pesquisa').find(":text:visible").val();
  console.log(search);    
});

JSFiddle

    
asked by anonymous 16.04.2015 / 18:30

1 answer

4

Your selector can return several items (since you're doing the following with this: :text:visible = select all inputs with type equal text and make it visible), then you should do a each in them pre-processing one by one and taking their respective values, since this seems to be their intention, something similar to this: / p>

$("#nome,#email").change(function() {
  $('#form_pesquisa').find(":text:visible").each(function(i) {
    console.log($(this).val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><formid='form_pesquisa'><labelfor='nome'>Nome</label><inputtype='text'name='nome'id='nome'/><labelfor='email'>Email</label><inputtype='text'name='email'id='email'/></form>

Online sample in jsFiddle.

The way that you were doing while doing a .val() on a selector would always return the value ( value ) of index item 0 (the first).

As already described in .val() documentation : " Get the current value of the first element in the set of matched elements. ", which in literal translation would be:" Gets the current value of the first element in the grouped element set. "

    
16.04.2015 / 18:42