Accessing the original object inside each
I want to check or uncheck all the ch开发者_运维知识库eckboxs the following code works for me
$( '#chkboxall' ).live( 'change', function() {
objs=$(document).find('#chkbox');
objs.each(function(){
$(this).attr( 'checked', $(this).is( ':checked' ) ? '' : 'checked' );
});
});
But instead of using $(this).is( ':checked' ) ? '' : 'checked'
i want to get the status of original checkbox that i have checked ie status of $('#chkboxall' ). How can i do that inside each?
Krishnik
You can shorten it without the .each()
here (since .attr()
can run on every element in the set already):
$('#chkboxall').live('change', function() {
$(document).find('#chkbox').attr('checked', this.checked);
});
However this isn't valid, you have a repeated chkbox
id
attribute which is invalid. Give those elements a class instead, like this:
<input name="blah" class="chkbox" type="checkbox" />
Then use a .class
selector in your code:
$('#chkboxall').live('change', function() {
$('.chkbox').attr('checked', this.checked);
});
For others finding this in a different situation, to get a reference to the "outer this
" inside a .each()
, just set a variable, like this:
$('#chkboxall').live('change', function() {
var thing = this;
$('.chkbox').each(function(){
//thing = the outer this, the #chkboxall element
});
});
精彩评论