thkang
thkang

Reputation: 11543

How do I extract values from <input> tags with same name?

I have either

1) multiple <input type="checkbox"> tags which have same name

2) <input type="radio"> tags which have same name

2) is trivial case, since radio buttons with same name can have only one button clicked.

the problem is case 1). here's what I came up with:

$('input[type="checkbox"]').click( function() {
  var value = $(this).val();
  alert(value);
});

with this, value stores only one item. If user have checked multiple items in same checkbox, how can I retrieve them?

Upvotes: 0

Views: 157

Answers (3)

Nishu Tayal
Nishu Tayal

Reputation: 20840

You can get checked values like this :

HTML :

<input type="checkbox" name="checkboxes" checked="checked" title="1" value="1" />
<input type="checkbox" name="checkboxes" title="2" value="2"/>
<input type="checkbox" name="checkboxes" checked="checked" title="3" value="3"/>
<input type="checkbox" name="checkboxes" title="4" value="4"/>

Script:

var val = []
$("input[name='checkboxes']:checked").each(function(i){
      val[i] = $(this).val();
});

console.log(val);

Here is the working demo : http://jsfiddle.net/56XTZ/

Upvotes: 0

bipen
bipen

Reputation: 36531

using jquery :checkbox selects all elements of type checkbox., :checked selects checked checkbox. so you can combine this and use loop to get the values...

try this

$(':checkbox').click( function() {
   var val = [];
    $(':checkbox:checked').each(function(i){
      val[i] = $(this).val();
    });

   console.log(val);
});

fiddle here

Upvotes: 0

Jonathan de M.
Jonathan de M.

Reputation: 9808

Try the following

$('input[type="checkbox"]').click( function() {
    stack = [];
    $('input[type="checkbox"]').each(function(){

        if($(this).is(':checked')){
            stack.push($(this).val())
        }
    })
    console.log(stack)
});

demo

Upvotes: 1

Related Questions