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.
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
. For example, the checkbox could be changed using the keyboard. 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" /> 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.