Javascript on tick or on untick events for a checkbox?

风流意气都作罢 提交于 2019-12-22 16:32:33

问题


Is it possible to fire an event when a checkbox is ticked, and a different one when it's unticked?

At the moment I'm using

$("#booking_checkboxes").on("change", "input", function(){});

but I'd like to know if the checkbox just changed to be ticked, or just changed to be unticked. What's the easiest way to do this?


回答1:


Nope, the same event is fired in both cases. You'd have to check for the value of the input in the event callback:

$("#booking_checkboxes").on("change", "input", function(){
  if (this.checked) {

  } else {

  }
});



回答2:


$("#booking_checkboxes").on("change", "input", function(){
   if (this.checked){
     // do what you want for when the element is checked

     // if you need to, you can trigger a custom event here..
     $('someelement').trigger('check_event');
   } else {
     // do what you want for when the element is NOT checked

     // if you need to, you can trigger a custom event here..
     $('someelement').trigger('uncheck_event');
   }
});


来源:https://stackoverflow.com/questions/9963323/javascript-on-tick-or-on-untick-events-for-a-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!