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

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


当前回答

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

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

其他回答

通过名称获取无线电值

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

只需使用单击事件 我的复选框id是CheckAll

     $('#CheckAll').click(function () {

        if ($('#CheckAll').is(':checked') == true) {

             alert(";)");
      }
    });

如果你使用<label for="cbId">cb name</label>,大多数答案都不会捕获它(假设)。这意味着当您单击标签时,它将选中复选框,而不是直接单击复选框。(不完全是这个问题,但各种搜索结果往往会出现在这里)

<div id="OuterDivOrBody">
    <input type="checkbox" id="checkbox1" />
    <label for="checkbox1">Checkbox label</label>
    <br />
    <br />
    The confirm result:
    <input type="text" id="textbox1" />
</div>

在这种情况下,你可以使用:

jQuery的早期版本:

$('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

jQuery 1.6.4的JSFiddle例子

jQuery 1 + 7。

$('#checkbox1').on('change', function() { 
    // From the other examples
    if (!this.checked) {
        var sure = confirm("Are you sure?");
        this.checked = !sure;
        $('#textbox1').val(sure.toString());
    }
});

JSFiddle的例子与最新的jQuery 2.x

添加了jsfiddle示例和带有可点击复选框标签的html

// 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;
    });
});

Try

checkbox1。Onclick = e => { 如果checkbox1 (! checkbox1.checked)。check = !confirm(“你确定吗?”); textbox1。Value = checkbox1.checked; } <input type="checkbox" id="checkbox1" /><br /> . <input type="text" id="textbox1" value= " false " />