简体   繁体   English

更改之前是否有监听器可以执行输入复选框

[英]Is there a listener for input checkbox to execute before change

I am having a checkbox and I could perform some operations when the checkbox is clicked using onchange function. 我有一个复选框,当使用onchange函数单击该复选框时,我可以执行一些操作。 But, what I need is, I have to prompt a popup/warning like, If you click the checkbox, some irreversible change could happen. 但是,我需要的是,我必须提示一个弹出窗口/警告,例如,如果单击复选框,则可能会发生一些不可逆的变化。 If the user clicks ok in the popup go on with the onchange function, else if the user clicks cancel, undo the change operation. 如果用户在弹出窗口中单击“确定”,则继续使用onchange函数,否则,如果用户单击“取消”,则撤消更改操作。 Is there a way to do this? 有没有办法做到这一点?

var checkbox = document.getElementById('myCheckbox');

checkbox.addEventListener('change', firePrompt);

function firePrompt(e) {
  if (e.target.checked) {
    setTimeout(function() {
      var result = confirm('Proceed?');
      if (result) {
        alert('User said OK');
      } else {
        alert('User said no!');
        e.target.checked = false;
      }
    }, 5)
  }
}

I had to add a setTimeout as firePrompt was immediately fired and wouldn't display the tick until the User had either clicked OK or Cancel . 我必须添加一个setTimeout因为firePrompt立即被触发,并且直到用户单击OKCancel时才显示刻度。

Here's a JSFiddle 这是一个JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM