How can I prevent the default checkbox event from overriding the jQuery validation / cancellation 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 box. It works great, unless the user clicks on this checkbox. Then it does not work. 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; } 
+6
source share
4 answers

You can use event.stopPropagation to avoid the click input#myContacts , which extends to the tr event event. Also, I can't believe that you mix jQuery and DOM this way when you should use jQuery events.

 $(document).ready(function(){ $("input#myContacts").click(function(e){ e.stopPropagation(); }); }); 
+8
source

Without HTML showing why this function works, it's hard to say. JsFiddle will be helpful. Just speculation, but maybe you click the checkbox that checks it, but the click event immediately calls this function, which cancels it?

0
source
  <tr class="checkBox">...</tr> $(document).ready(function () { $('tr.checkBox').live('click', function (e) { if (e.target.type !== 'checkbox') { $('input#myContacts').attr("checked", function () { return !$(this).prop('checked'); }); //Or $(this).find('input#myContacts').attr("checked", function () { return !$(this).prop('checked'); }); } }); }); 
0
source

Solution 1: http://jsfiddle.net/qmdGK/3/ (using two table cells, but only binding to a text cell)

Solution 2: http://jsfiddle.net/qmdGK/4/ (using stopPropagation () in the click event)

Both use jQuery to bind the event to an element, which is preferred.

0
source

Source: https://habr.com/ru/post/916148/


All Articles