frenchie
frenchie

Reputation: 52017

jquery getting index of selected checkbox

I have some HTML like this:

<div id="Myclass">

 <div class="Wrapper">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
 </div>

 <div class="Wrapper">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
    <input type="checkbox" class="SomeCheckboxClass">
 </div>

</div>

I want to find the index of a the selected textbox, if any.

For now, I wrote this:

$('#MyClass .Wrapper').each(function () {

    Index = 0;

    $(this).find('.SomeCheckboxClass').each(function () {
        if ($(this).attr('checked')) {
            Index = $(this).index();
        }
    });

    SomeFunction(Index);
});

Is there a better way to do this?

Thanks.

Upvotes: 1

Views: 7201

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87083

$('#Myclass .Wrapper').each(function() {
    var Index = $('.SomeCheckboxClass:checked', this).index();
    SomeFunction(Index);
});

​DEMO

You can also use map()

$('#Myclass .Wrapper').map(function() {
    var Index = $('.SomeCheckboxClass:checked', this).index();
    SomeFunction(Index);
});

DEMO

Upvotes: 1

pimvdb
pimvdb

Reputation: 154918

You can use .map: http://jsfiddle.net/p4nD7/1/.

$("#Myclass .Wrapper :checkbox:checked").map(function() {
  return $(this).index();  // index in parent
}).each(function() {
  "use strict";  // no object for `this` but just the primitive value
  SomeFunction(this);
});

Upvotes: 5

Stefan Fandler
Stefan Fandler

Reputation: 1141

Why not just do this:

$('.checkbox').click(function() {
    if($(this).attr('checked')) {
        SomeFunction($(this).index());
    }
});

Upvotes: 0

Related Questions