简体   繁体   中英

Don't check checkbox when clicking a button inside the label

I have the following setup (simplified), inside the label I have some images, which activate JavaScript functions, is there a way to ignore the click on the label if the user clicks on one of these images?

<input type="checkbox" id="i_87" name="image[]" />
<label for="i_87" style="width:500px;height:500px;background-image:url('image.jpg');">
    <img src="bt1.jpg" onClick="somefun1()" />
    <img src="bt2.jpg" onClick="somefun2()" />
</label>

Just to clarify, I don't want it to check the checkbox when the images are clicked, but it SHOULD check the checkbox when anywhere else is clicked!

You must prevent the default action. The easiest way is to return false from your functions. Here is an example, bypassing your function (just return false from them and you should get the same behavior). Tested in Chrome, but it's a pretty standard practice.

<input type="checkbox" id="i_87" name="image[]" />
<label for="i_87" style="width:500px;height:500px;background-image:url('image.jpg');">
    <img src="bt1.jpg" onclick="return false;" />
    <img src="bt2.jpg" onclick="return false;" />
</label>

This has nothing to do with CSS. In order to stop the label from checking the related checkbox, you will either have to remove the for="i_87" attribute, or use Javascript to stop the event from performing its default action.

In jQuery, that would be something like this:

$("label").on("click",function(evt) {
     evt.preventDefault();
});

This should theoretically then allow the click event to pass on to your images but cancel the label's default action.

从标签中删除for="i_87"

Throwing this out there as a possibility . . . could you just move the buttons outside of the label?

<input type="checkbox" id="i_87" name="image[]" />
<label for="i_87" style="width:500px;height:500px;background-image:url('image.jpg');" />
<img src="bt1.jpg" onClick="somefun1()" />
<img src="bt2.jpg" onClick="somefun2()" />

It would probably take a little tweaking to get it to look the same, but it would make a whole lot more sense than putting the buttons into the label and then suppressing the default behavior of the label, but only for those buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM