Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent default checkbox event from overriding my jQuery check/uncheck function?

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;
}
like image 987
John Anderson Avatar asked May 19 '12 07:05

John Anderson


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 uncheck a specific checkbox in jQuery?

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.

How can checked checkbox in jQuery?

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);

Which method is used to know whether the checkbox is toggled on or off?

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.


1 Answers

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();
  });
});
like image 157
Alexander Avatar answered Sep 18 '22 10:09

Alexander