开发者

which event should I fire a change on?

In an html form I have a checkbox that has a label. When you click the checkbox or its label, it toggles the checkedness of the checkbox. It's wrapped in a <div>.

I am using jquery to hide another element of the form if the checkbox is checked. Originally I was using the .click() function of the wrapping div. But I noticed that you could click between the checkbox and the label ( which is still within the div), and get the other to hide, even though the checkbox was not checked. (Also, for some reason, clicking on the label caused the element to hide then reappear, but I don't think I need to open that can of worms).

I was thinking that instead of the click() of the div, I should look at both the checkbox and the div separately. Then I thought I just might look for something like an onChange event for the ch开发者_运维问答eckbox itself, which clicking the label should affect. Then I thought that people have probably solved this problem before and I should not try to re-invent the wheel.

What's a simple way to keep the checkbox value and the hide/show state of my element in sync, when two different elements can change the checkbox status?


Attach a onclick event to the checkbox (a onchange event works too). Whether you click on the checkbox itself, or its label, the event handler will fire. Just make sure that the label's for attribute contains the id of the checkbox.

http://jsfiddle.net/FishBasketGordo/GJbce/


An onChange event for the checkbox will probably serve your needs well in this instance.


Try using the .change() function on the checkbox input.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜