get text fields that are not empty

Let’s say that I have an HTML structure like this:

<div class="container">   <input type="text" class="userInfo" name="first_name1" value="First name 1" />   <input type="text" class="userInfo" name="first_name2" value="First name 2" />
</div>


<div class="container">   <input type="text" class="userInfo" name="first_name3" value="First name 3" />   <input type="text" class="userInfo" name="first_name4" value="First name 4" />
</div>

How do I get all the text fields that are not empty when the user clicks on a button with jQuery?

Once I get them, I want to construct a key-value pair string (concatenated with &) to be sent as parameter to a URL for example:

"first_name1='First name 1&first_name2=First name 2'....

solution

You could use the .filter() method to find all the input elements that contain values:

Example Here

var $fieldsWithValues = $('input').filter(function () {   return this.value;
});

Based on your edit, you can construct the query string by using the $.param() function:

Example Here

var params = {};
var $fieldsWithValues = $('input').filter(function () {   return this.value.trim();
}).each(function () {   params[this.name] = this.value;
});


console.log($.param(params));

The above would log:

"first_name1=First+name+1&first_name2=First+name+2&first_name3=First+name+3&first_name4=First+name+4"