$(document).ready(function() { //set initial state. $('#textbox1').val($(this).is(':checked')); $('#checkbox1').change(function() { $('#textbox1').val($(this).is(':checked')); }); $('#checkbox1').click(function() { if (!$(this).is(':checked')) { return confirm("Are you sure?"); } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="checkbox" id="checkbox1"/><br /> <input type="text" id="textbox1"/>

这里.change()用复选框状态更新文本框值。我使用.click()来确认取消检查的操作。如果用户选择cancel,则恢复选中标记,但.change()在确认之前触发。

这会使内容处于不一致的状态,当选中复选框时,文本框显示为false。

我如何处理取消和保持文本框值与检查状态一致?


当前回答

对我来说,这很有效:

$('#checkboxID').click(function () {
    if ($(this).attr('checked')) {
        alert('is checked');
    } else {
        alert('is not checked');
    }
})

其他回答

如果你正在使用iCheck Jquery使用下面的代码

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });

单击复选框并检查同一事件循环中的值是问题所在。

试试这个:

$('#checkbox1').click(function() {
    var self = this;
    setTimeout(function() {

        if (!self.checked) {
            var ans = confirm("Are you sure?");
            self.checked = ans;
            $('#textbox1').val(ans.toString());
        }
    }, 0);
});

演示:http://jsfiddle.net/mrchief/JsUWv/6/

我不明白为什么每个人都把这件事搞得这么复杂。 这就是我所做的一切。

if(!$(this).is(":checked")){ console.log("on"); }

试试这个

$('#checkbox1').click(function() {
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = sure;
            $('#textbox1').val(sure.toString());
        }
    });
// this works on all browsers.

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function(e) {
        this.checked =  $(this).is(":checked") && !!confirm("Are you sure?");
        $('#textbox1').val(this.checked);
        return true;
    });
});