I have been asked to disable the \"ticking\" of a checkbox. I am not being asked to disable the checkbox, but to simply disable the \"ticking\".
In other w
HTML api's execute before JavaScript. So you must use JavaScript to undo HTML's changes.
event.target.checked = false
Strictly speaking: we cannot "stop" the checkbox from being ticked. Why not? Because "being ticked" exactly means that the DOM's, HTML <input>
element has a checked
property value of true
or false
, which is immediately assigned by the HTML api
console.log(event.target.checked) // will be opposite of the previous value
So it's worth explicitly mentioning this HTML api is called before scripts. Which is intuitive and should make sense, because all JavaScript files are themselves the assignment of a <script>
element's attribute src
, and the ancestral relationship in the DOM tree, between your <input>
in question, and the <script>
element running your JavaScript, is extremely important to consider.
The HTML assigned value has not yet been painted before we have a chance to intercept the control flow (via JS file like jQuery), so we simply re-assign the checked
property to a boolean value we want: false
(in your case).
So in conclusion, we CAN, in-effect, "stop" the checkbox from being checked, by simply ensuring that the checked
property is false
on the next render and thus, won't see any changes.
From my point of view it is as simple as:
$(this).prop('checked', !$(this).prop('checked'));
Works both for checked and unchecked boxes
Add this to click event in js file
event.stopPropagation();
Best solution I've come up with:
$('input[type="checkbox"]').click(function(event) {
var $checkbox = $(this);
// Ensures this code runs AFTER the browser handles click however it wants.
setTimeout(function() {
$checkbox.removeAttr('checked');
}, 0);
event.preventDefault();
event.stopPropagation();
});
Wrap the checkbox with another element that somehow blocks pointer events (probably via CSS). Then, handle the wrapper's click event instead of the checkbox directly. This can be done a number of ways but here's a relatively simple example implementation:
$('input[type="checkbox"').parent('.disabled').click( function() {
// Add in whatever functionality you need here
alert('Break');
});
/* Insert an invisible element that covers the checkbox */
.disabled {
position: relative;
}
.disabled::after {
content: "";
position: absolute;
top: 0px;
left: 0px;
right: 0px;
bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Only wrapped checkboxes are "disabled" -->
<input type="checkbox" />
<span class="disabled"><input type="checkbox" /></span>
<input type="checkbox" />
<span class="disabled"><input type="checkbox" /></span>
<span class="disabled"><input type="checkbox" /></span>
<input type="checkbox" />
Note: You could also add the wrapper elements programmatically, if you would like.
Try
event.stopPropagation();
http://jsfiddle.net/DrKfE/3/