Click on a div to toggle a checkbox inside of it using javascript

前端 未结 6 901
耶瑟儿~
耶瑟儿~ 2020-12-15 18:50

This seems to be a simple problem, but I dont use alot of javascript.

I have a div, with a checkbox in it, and would like the whole div to toggle the checkbox. This

6条回答
  •  清歌不尽
    2020-12-15 19:04

    The root of the problem is that when you click on the checkbox, the click event is propagated up the DOM to parent elements.

    So the checkbox handles the click event by toggling itself, and then the DIV receives the click event and toggles the checkbox again.

    The simplest solution would be to stop propagation of the event, by adding this to the input element:

    onClick="event.stopPropagation();"
    

    While this is defined in the W3C DOM Level 2 Event Model, it may not be supported in all browsers so you may want to use a cross-browser library like Prototype or jQuery to ensure compatibility.

提交回复
热议问题