I have a list of checkboxes inside a table with a simple jQuery function that allows the user to click anywhere in the table row to check/uncheck the checkbox. It works great, except when the user actually clicks on the checkbox. It doesn't work then. Any ideas? Here is my code:
HTML:
<tr onClick="checkBox()">...</tr>
jQuery:
function checkBox() {
var ischecked = $('input#myContacts').attr("checked");
if(ischecked)
{
$('input#myContacts').attr("checked", false);
}
else
{
$('input#myContacts').attr("checked", true);
}
return false;
}
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.
By using jQuery function prop() you can dynamically add this attribute or if present we can change its value i.e. checked=true to make the checkbox checked and checked=false to mark the checkbox unchecked.
To check whether a Checkbox has been checked, in jQuery, you can simply select the element, get its underlying object, instead of the jQuery object ( [0] ) and use the built-in checked property: let isChecked = $('#takenBefore')[0]. checked console. log(isChecked);
prop(): This method provides an simple way to track down the status of checkboxes. It works well in every condition because every checkbox has checked property which specifies its checked or unchecked status.
You can use event.stopPropagation
to avoid your input#myContacts
's click event propagates to the tr
's click event. Also, I can't believe you are mixing jQuery and DOM in that way yet, when you should be using jQuery Events.
$(document).ready(function(){
$("input#myContacts").click(function(e){
e.stopPropagation();
});
});
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