Reputation: 52017
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
Reputation: 87083
$('#Myclass .Wrapper').each(function() {
var Index = $('.SomeCheckboxClass:checked', this).index();
SomeFunction(Index);
});
You can also use map()
$('#Myclass .Wrapper').map(function() {
var Index = $('.SomeCheckboxClass:checked', this).index();
SomeFunction(Index);
});
Upvotes: 1
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
Reputation: 1141
Why not just do this:
$('.checkbox').click(function() {
if($(this).attr('checked')) {
SomeFunction($(this).index());
}
});
Upvotes: 0