I'm using a checkbox and I want people to be able to check/uncheck it. However, when they uncheck it, I'm using a jQueryUI modal popup to confirm that they really want to do that. Thus they can click OK or Cancel, and I want my checkbox to be unchecked only if they click OK.
That's why I would like to catch the uncheck event to prevent the checkbox from being visually unchecked, and uncheck it myself programmatically if the user happens to click on OK.
How could I do that ?
PS: I know I could re-check it after if the user clicks on Cancel but that would trigger the check
event which I do not want.
In this article, you are going to learn how you can prevent a checkbox from being unchecked using JavaScript preventDefault() method without disableing it. Use the preventDefault() method to stop the default behavior of a particular element.
$(':checkbox[readonly]'). click(function(){ return false; });
preventDefault() to stop checkbox from been toggled. You can event add some logic before $event. preventDefault() to determin whether the checkbox should be prevent from changing status.
//This will make all read-only check boxes truly read-only $('input[type="checkbox"][readonly]'). on("click. readonly", function(event){event. preventDefault();}).
$("#checkboxID").on("click", function (e) { var checkbox = $(this); if (checkbox.is(":checked")) { // do the confirmation thing here e.preventDefault(); return false; } });
Something like:
$("#test").on('change', function() { this.checked=!this.checked?!confirm('Really uncheck this one ?'):true; });
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With