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

use*_*572 18 javascript checkbox jquery events

我正在使用复选框,我希望人们能够检查/取消选中它.但是,当他们取消选中它时,我正在使用jQueryUI模式弹出窗口来确认他们确实想要这样做.因此,他们可以点击OKCancel,我希望我的复选框只有在他们点击时才能取消选中OK.
这就是为什么我想要捕获uncheck事件以防止在视觉上取消选中复选框,并且如果用户碰巧点击则以编程方式取消选中它OK.

我怎么能这样做?

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

Umu*_*acı 23

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

  • 我认为这个答案可能与提问者想要的相反。实施它使我无法选中复选框,而不是取消选中它们。我加了“!” 到 if 条件,但一切都很好。 (2认同)

ade*_*neo 12

就像是:

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

小提琴

  • +1很好.你可以使它更短/更清晰:`this.checked = this.checked || !确认('真的取消选中这个?');` (2认同)

Pra*_*aju 10

纯 CSS 解决方案

选择复选框,如 -

input[type="checkbox"] {
    pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)

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