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

Asked

Viewed 2,229 times

4

Currently I 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 possessing an email and a phone, my doubt and the next, I use a tablist who has a form and in that form i can only get the first field filled and not all, in case I need to get all fields that are filled, example:

<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

1 answer

4


Your selector can return multiple items (since you are doing the following with this: :text:visible = select all the inputs with type equal to text and that are visible), so you should make a each and taking their respective values, since this seems to be their intention, something similar to this:

$("#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>
<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>

Online example in jsFiddle.

The way you were doing when making a .val()in a selector it will always return the value (value) of index item 0 (the first).

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

  • 1

    success, thanks for the knowledge, for a long time I use . val(); but I had forgotten to use each() to go through the fields picking up the values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.