King RG
King RG

Reputation: 510

Get values of multiple fields by names in jQuery/JS

Currently I have this code for getting multiple weight

 <input type="number" name="myWeight" id="1A">
 <input type="number" name="myWeight" id="1B">
 <input type="number" name="myWeight" id="1C">

This is my current javascript lines

var selWeight = []; 
$('input[name="myWeight"]').each(function() {
    selWeight.push($(this).val());
});
alert(selWeight);

This current code is working fine and this is the output of this code

enter image description here

enter image description here

But the problem is if the user only enters this

enter image description here

and this is the output

enter image description here

What I only want is to get the text field that is not empty.

Upvotes: 0

Views: 554

Answers (2)

Aksen P
Aksen P

Reputation: 4599

Try to replace

$('input[name="myWeight"]').each(function() {
    selWeight.push($(this).val());
});

with next:

$('input[name="myWeight"]').each(function() {
    if ($(this).val() != '') {
        selWeight.push($(this).val());
    }
});

Upvotes: 1

King RG
King RG

Reputation: 510

This works fine thank you @Shree

   if($(this).val() != '') 
       selWeight.push($(this).val());

Upvotes: 1

Related Questions