SyAu
SyAu

Reputation: 1681

jQuery - Get the index of selected check box

jQuery 1.7.1 - I have a check box column and would like to get the index of selected boxes as an array or iterate through each checkbox - check whether its selected or not, if selected get the index.

HTML

<tr>
  <td><input type="checkbox" class="it" name="it"></td>
</tr>
<tr>
  <td><input type="checkbox" class="it" name="it"></td>
</tr>

Upvotes: 0

Views: 23240

Answers (3)

emgee
emgee

Reputation: 520

This is an old posting but I came across it while helping out elsewhere, just wanted to add some code regarding your request of not having an explicit index var for keeping track of the index. The value returned from index() is zero-based.

var myCheckboxes = $("input[type=checkbox].it");

myCheckboxes.each(function(){
    alert(myCheckboxes.index(this));
    // do whatever you need with the index of the checkbox
}

More on .index() can be found here: http://api.jquery.com/index/

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150080

If you use the .each() method jQuery will pass the index as an argument to the callback function you supply. (You'll probably see a lot of code around that uses .each() without parameters on the callback, but that's just because you often don't need to know the index - but it's there for when you do.) Also when calling your function jQuery sets this to the current element:

$(".it").each(function(i) {
   if (this.checked) {
       alert("Checkbox at index " + i + " is checked.");
   }
});

Noting that the index is zero-based, and in case it's not obvious it is the index within the set of elements that matched the selector you supplied (not within all elements in the document).

Note also that above I'm selecting elements by class, but you could select by the name attribute:

$('input[name="it"]')

Upvotes: 4

aroth
aroth

Reputation: 54846

var index = 0;
$('.it').each(function() {
    if (this.checked) {
        alert("Box is checked at index=" + index);
    }
    index++;
});

Example: http://jsfiddle.net/bvUND/

Upvotes: 2

Related Questions