Simple question regarding doing action on checkbox click in jquery
I must have looked at 10-15 tutorials on t开发者_StackOverflow中文版his already but just cannot get this to work, so in my .js I have:
jQuery('#sports : checkbox').click(function() {
alert('it works');
});
and in my .html doc I have:
<input type="checkbox" name="sports" />
It just won't work, no matter what I try and I have tried every variation I can come up with, the input checkbox isn't in a DIV or anything (but I am also curious how to reference it if it is in a div.. just for a control on this test, I have tried this and it works fine (where "testdiv" is a name of a DIV in my document:
jQuery('#testdiv').click(function() {
alert('it works');
});
Without spaces:
jQuery('#sports:checkbox')
and you have to give the input element the correct ID (#
selects elements with the corresponding ID):
<input type="checkbox" name="sports" id="sports" />
Or you search for attribute name
:
jQuery('input:checkbox[name=sports]')
Your selector is off a bit, you need this instead (for your current markup):
jQuery(':checkbox[name=sports]').click(function() {
alert('it works');
});
When you do a #sports : checkbox
selector it's looking for...well I'm not sure what, but #sports :checkbox
is looking for a <input type="checkbox" />
inside an element with id="sports"
. The [name=sports]
is using the attribute-equals selector. You can find a full list of selectors here.
Have you tried adding an id to your html? The # in jQuery refers you are selecting an id.
精彩评论