$(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。

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


当前回答

试试这个

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

其他回答

通过名称获取无线电值

 $('input').on('className', function(event){
        console.log($(this).attr('name'));
        if($(this).attr('name') == "worker")
            {
                resetAll();                 
            }
    });

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

试试这个:

$('#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/

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

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

Demo

使用mousedown

$('#checkbox1').mousedown(function() {
    if (!$(this).is(':checked')) {
        this.checked = confirm("Are you sure?");
        $(this).trigger("change");
    }
});
// 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;
    });
});