How to trigger checkbox click event even if it is checked with Javascript code?

I have many checkboxes on my page, and there is a checkbox to select all, which checks all the checkboxes. Somehow I want to emulate this checkbox click event, even if it is checked / unchecked using the "Select All" button. How can i do this?

+69
javascript jquery checkbox javascript-events dom-events
Jan 24 '11 at 10:25
source share
7 answers

You can use jQuery .trigger() method. See http://api.jquery.com/trigger/

eg:.

 $('#foo').trigger('click'); 
+100
Jan 24 2018-11-11T00:
source share

Obtaining verification status

 var checked = $("#selectall").is(":checked"); 

Then for installation

 $("input:checkbox").attr("checked",checked); 
+13
Jan 24 '11 at 10:32
source share

You can also use the .change() function

eg:.

 $('form input[type=checkbox]').change(function() { console.log('hello') }); 
+8
Oct 24 '12 at 18:35
source share

no gQuery

document.getElementById ('your_box') OnClick () ;.

I used a specific class on my checkboxes.

 var x = document.getElementsByClassName("box_class"); var i; for (i = 0; i < x.length; i++) { if(x[i].checked) x[i].checked = false; else x[i].checked = true; x[i].onclick(); } 
+5
Apr 21 '15 at 13:54 on
source share

The trigger function from jQuery may be your answer.

jQuery docs says: Any event handlers associated with .on () or one of its shortcut methods are fired when the corresponding event occurs. However, they can be started manually using the .trigger () method. The call for .trigger () is performed by the handlers in the same order as they would be if the event were called by the user by the user

Thus, the best solution for a single line should be:

 $('.selector_class').trigger('click'); //or $('#foo').click(); 
+3
Dec 6 '15 at 21:00
source share

You can also use this, I hope you can serve them.

 $(function(){ $('#elements input[type="checkbox"]').prop("checked", true).trigger("change"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div id="elements"> <input type="checkbox" id="item-1" value="1"> Item 1 <br /> <input type="checkbox" id="item-2" value="2" disabled> Item 2 <br /> <input type="checkbox" id="item-3" value="3" disabled> Item 3 <br /> <input type="checkbox" id="item-4" value="4" disabled> Item 4 <br /> <input type="checkbox" id="item-5" value="5"> Item 5 </div> 
+2
Jul 19 '19 at 15:15
source share
  $("#gst_show>input").change(function(){ var checked = $(this).is(":checked"); if($("#gst_show>input:checkbox").attr("checked",checked)){ alert('Checked Successfully'); } }); 
0
Aug 19 '19 at 3:39
source share



All Articles