Javascript 防止复选框在单击时取消选中(不禁用或只读)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12138821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:11:51  来源:igfitidea点击:

Prevent checkbox from unchecking when clicked (without disable or readonly)

javascriptjqueryeventscheckbox

提问by user1498572

I'm using a checkbox and I want people to be able to check/uncheck it. However, when they uncheck it, I'm using a jQueryUI modal popup to confirm that they really want to do that. Thus they can click OKor Cancel, and I want my checkbox to be unchecked only if they click OK.
That's why I would like to catch the uncheck event to prevent the checkbox from being visually unchecked, and uncheck it myself programmatically if the user happens to click on OK.

我正在使用复选框,我希望人们能够选中/取消选中它。但是,当他们取消选中它时,我使用 jQueryUI 模态弹出窗口来确认他们真的想要这样做。因此,他们可以单击OKCancel,并且我希望仅当他们单击 时才取消选中我的复选框OK
这就是为什么我想捕捉 uncheck 事件以防止复选框在视觉上被取消选中,如果用户碰巧点击OK.

How could I do that ?

我怎么能那样做?

PS: I know I could re-check it after if the user clicks on Cancelbut that would trigger the checkevent which I do not want.

PS:我知道我可以在用户点击后重新检查它,Cancel但这会触发check我不想要的事件。

回答by Umur Kontac?

$("#checkboxID").on("click", function (e) {
    var checkbox = $(this);
    if (checkbox.is(":checked")) {
        // do the confirmation thing here
        e.preventDefault();
        return false;
    }
});

回答by adeneo

Something like:

就像是:

$("#test").on('change', function() {
    this.checked=!this.checked?!confirm('Really uncheck this one ?'):true;
});
?

FIDDLE

小提琴

回答by Pranjal jaju

Pure CSS Solution

纯 CSS 解决方案

Select Checkbox like -

选择复选框,如 -

input[type="checkbox"] {
    pointer-events: none;
}

Works Pretty well, and now you can toggle your checkbox on any element click of your choice.

效果很好,现在您可以在您选择的任何元素单击上切换复选框。

回答by Yaw shadi

   $("#checkboxID").click(function(e) { 
      var checkbox = $(this);
      if (checkbox.is(":checked")) {
       //check it 
      } else {
       // prevent from being unchecked
        this.checked=!this.checked;
      }
   });

回答by Julian

How about using the HTML disabled property?

如何使用 HTML disabled 属性?

<input type="checkbox" name="my_name" value="my_value" disabled> My value<br>

Link:

关联:

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Property/disabled

https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XUL/Property/disabled

回答by AdityaParab

$("#yourCheckBoxId").on('change',function(e){
    e.preventDefault();
    $("#yourPopDiv").popup();
});

preventDefault()will disable default behavior of your input[type="checkbox"]

preventDefault()将禁用您的默认行为 input[type="checkbox"]

And on your popup div

在你的弹出 div 上

$("#ok").on('click',function(){
    $("#yourCheckBoxId").attr("checked",true);
});