最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Bind JavaScript jQuery click event on label AND on checkbox simultaneously - Stack Overflow

programmeradmin3浏览0评论

I'm using labels for my form, like this :

<label for="foo" id="bar">Label</label>
<input type="checkbox" id="foo" />

I want to hide an element when the user uncheck the box, and show it otherwise.

The problem is, if I bind the click event to "foo", it'll only works when the user clicks on the checkbox itself and not on the label. Therefore, do I also need to bind a click event on the label ? Or should I enclose both elements within a span ? My HTML already contains 2344 elements, so I'd like to do it without adding anything, and without doubling the JavaScript code or the selector, if possible.

I'm using labels for my form, like this :

<label for="foo" id="bar">Label</label>
<input type="checkbox" id="foo" />

I want to hide an element when the user uncheck the box, and show it otherwise.

The problem is, if I bind the click event to "foo", it'll only works when the user clicks on the checkbox itself and not on the label. Therefore, do I also need to bind a click event on the label ? Or should I enclose both elements within a span ? My HTML already contains 2344 elements, so I'd like to do it without adding anything, and without doubling the JavaScript code or the selector, if possible.

Share Improve this question asked Feb 8, 2012 at 15:34 WillyWilly 7632 gold badges8 silver badges29 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

Instead of binding with the click() event, you should bind using the change() event, then however this change is triggered the outcome will be the same:

$('#foo').change(
    function(){
        // do whatever
    });

References:

  • change().

The change event should fire for the input whether the label or input is clicked:

$("#foo").change(function () { ... });

Example http://jsfiddle.net/andrewwhitaker/6LMXW/

发布评论

评论列表(0)

  1. 暂无评论