1

I have a checkbox and the requirement is that when the user clicks it, instead of immediately changing its state, a modal window should pop up asking them a yes/no question. Depending on their answer, the checkbox should either become checked or remain unchecked.

I thought that this requirement should be handled using Event.preventDefault() but when I tried to do it I discovered that when I exit the event handler, the checkbox is reverted to its original state, regardless of my programmatic attempts to set the state in the handler.

$(function() {
  $(":checkbox").click(function(e) {
    e.preventDefault();
    $(this).prop("checked", confirm("Confirm to check the checkbox"));
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <label for="checkbox">Click me</label>
  <input type="checkbox" id="checkbox">
</form>

So how can I implement the required behavior?

1 Answer 1

3

The problem is because you called preventDefault() at all. You don't need it in this case as the checked state is entirely dependant on the outcome of the confirm() call.

Also note that you should use the change event, not click, when dealing with checkboxes. Try this:

$(function() {
  $(":checkbox").change(function(e) {
    $(this).prop("checked", confirm("Confirm to check the checkbox"));
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <label for="checkbox">Click me</label>
  <input type="checkbox" id="checkbox">
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.