简体   繁体   中英

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/

 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 . For example, the checkbox could be changed using the keyboard.
  • Better avoid inline event listeners. You can use addEventListener instead.

 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> 

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