简体   繁体   English

javascript通过单击标签确认选中复选框

[英]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" />&nbsp; Apply </label> </form> 

Some notes: 一些注意事项:

  • Better add the event listener to the element that changes (the checkbox), not its label. 最好将事件侦听器添加到更改的元素(复选框),而不是其标签。
  • Better listen to change event instead of click . 最好听change事件,而不要click For example, the checkbox could be changed using the keyboard. 例如,可以使用键盘更改复选框。
  • Better avoid inline event listeners. 最好避免内联事件侦听器。 You can use 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" /> &nbsp; Apply </label> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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