[英]javascript confirm when checking a checkbox by clicking on the label
I have a checkbox on a form that does something dangerous. 我的表单上有一个复选框,它做一些危险的事情。 So, I want to make sure the user is really sure when they check this item, but I don't want to warn them if they're unchecking the checkbox. 因此,我想确保用户在确定该项目时确实很确定,但是如果他们取消选中此复选框,则我不想警告他们。
My issue is this works fine if they click on the actual checkbox to uncheck it, but not the text of the label. 我的问题是,如果他们单击实际的复选框以取消选中它,而不是标签的文本,则可以正常工作。
http://jsfiddle.net/j2ppzpdk/ http://jsfiddle.net/j2ppzpdk/
function askApply() { if (document.getElementById("apply").checked) { var answer = confirm("Are you sure about that?"); if (!answer) { document.getElementById("apply").checked = false; } } }
<form> <label onclick="askApply();"> <input type="checkbox" name="apply" id="apply" value="1" /> Apply </label> </form>
Some notes: 一些注意事项:
change
event instead of click
. 最好听change
事件,而不要click
。 For example, the checkbox could be changed using the keyboard. 例如,可以使用键盘更改复选框。 addEventListener
instead. 您可以改用addEventListener
。 document.getElementById('apply').addEventListener('change', function() { if(this.checked) { var answer = confirm("Are you sure about that?"); if (!answer) { document.getElementById("apply").checked = false; } } });
<form> <label> <input type="checkbox" name="apply" id="apply" value="1" /> Apply </label> </form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.