At times there is a need to not disable and at the same time prevent checkbox from being checked or unchecked when clicked. In other words, the checkbox should be visible as a modifiable control but the user clicks should not change the state of the checkbox. In such cases, disabling the checkbox is not an option.
The following jQuery script would do the trick:
<!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>PreventCheckboxClickDemo</title> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('input[type="checkbox"]').click(function(e) { e.preventDefault(); e.stopPropagation(); }); }); </script> </head> <body> <table id="chkboxTable" border="1" onclick="alert('The table was clicked!')"> <tr> <td>Try unchecking this:</td> <td><input type="checkbox" id="first_chkbox" checked="checked" readonly/></td> </tr> <tr> <td>Try checking this:</td> <td><input type="checkbox" id="second_chkbox" /></td> </tr> </table> </body> </html>
Copy and paste the above HTML page in a Dynamic Web Project in Eclipse. Deploy and run it on any application server or web container. The following output should be displayed
Clicks on either of the checkboxes will be ignored because of e.preventDefault();
Whereas, e.stopPropagation();
will prevent the bubbling up of the click event to the parent table.
To understand event bubbling better, comment the line e.stopPropagation();
and open the page again in browser. Click on any of the checkboxes. You should see the following
This is because in the absence of the statement e.stopPropagation()
, the click event although fired on checkbox, propagates all the way up to the parent table where we have already set up an alert statement listening to it.
With bubbling, the event is first captured and handled by the innermost element and then propagated to outer elements.
Therefore, if the checkbox is nested inside a parent element, it is a good idea to call stopPropagation()
in conjunction with preventDefault()
.
See you in the next blog!
Thank you for It is simple but very useful code
This is especially useful when plotting a flot graph with checkbox-controlled data. If a flot graph has no data, it is not plotted and looks like an ugly block. To prevent this, I used your preventDefault tip and it works like a charm! Thanks a lot!
https://jsfiddle.net/1d4ocv3n/3/