Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent checkbox from unchecking when clicked (without disable or readonly)

Tags:

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.

like image 747
user1498572 Avatar asked Aug 27 '12 08:08

user1498572


People also ask

How do I stop a checkbox from being unchecked?

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.

How do I make a checkbox not clickable in HTML?

$(':checkbox[readonly]'). click(function(){ return false; });

How do you stop a checkbox being checked in angular 8?

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.

How do I make a check box read only?

//This will make all read-only check boxes truly read-only $('input[type="checkbox"][readonly]'). on("click. readonly", function(event){event. preventDefault();}).


2 Answers

$("#checkboxID").on("click", function (e) {     var checkbox = $(this);     if (checkbox.is(":checked")) {         // do the confirmation thing here         e.preventDefault();         return false;     } }); 
like image 160
Umur Kontacı Avatar answered Sep 17 '22 02:09

Umur Kontacı


Something like:

$("#test").on('change', function() {     this.checked=!this.checked?!confirm('Really uncheck this one ?'):true; }); ​ 

FIDDLE

like image 44
adeneo Avatar answered Sep 18 '22 02:09

adeneo