In this JSfiddle have I two forms.
This is duplicated twice
<form action="" method="post">
<input id="element" signed type="checkbox" checked>
<label for="element">x</label>
<but开发者_StackOverflow社区ton type="submit">Submit</button>
</form>
and the JQuery looks like this
$('form').live('submit', function(){
if ($("input[type=checkbox]").is(':checked')){
$("label").show();
}else{
$("label").hide();
}
return false;
});
I can't use ID's to distinguished between the forms, so I am left this $(this)
I suppose.
If the last form is removed, it works as it should, but the problem is to get it work with many without using ID's.
However if I change the code to
$('form').live('submit', function(){
if ($(this).("input[type=checkbox]").is(':checked')){
$(this).("label").show();
}else{
$(this).("label").hide();
}
return false;
});
It doesn't work.
What am I doing wrong?
$(this).("input[type=checkbox]")
is not valid code--you're using parens to invoke something, but have nothing in front of them to invoke. You need to call .find()
or .children()
off your jQuery-ized form:
$(this).find("input[type=checkbox]")
Here is a condensed version for you:
$( 'form' ).live( 'submit', function()
{
var $this = $( this );
$this.find( 'label' ).toggle( $this.find( 'input[type="checkbox"]' ).is( ':checked' ) );
return false;
} );
You need a method name.
You could use the find()
[docs] method, which searches all descendants:
$(this).find("label").show();
...or the children()
[docs] method, which only searches direct descendants.
$(this).children("label").show();
Your code could look like this:
$('form').live('submit', function(){
if ($(this).find("input[type=checkbox]").is(':checked')){
$(this).find("label").show();
}else{
$(this).find("label").hide();
}
return false;
});
$("input[type=checkbox]", this).is(':checked')
Try this:
$('form').live('submit', function(){
// Cache "this" reference
var $this= $(this);
if ($this.find("input[type=checkbox]").is(':checked')){
$this.find("label").show();
}else{
$this.find("label").hide();
}
return false;
});
精彩评论