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

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


当前回答

在JSFiddle中测试,并执行您所要求的。这种方法还有一个额外的好处,即当单击与复选框关联的标签时触发。

答:更新

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

    $('#checkbox1').change(function() {
        if(this.checked) {
            var returnVal = confirm("Are you sure?");
            $(this).prop("checked", returnVal);
        }
        $('#textbox1').val(this.checked);        
    });
});

最初的回答:

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

    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));        
    });
});

其他回答

试试这个:

    let checkbox = document.getElementById('checkboxId');
    if (checkbox.checked != true)
    {
        alert("select checkbox");
    }

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

 $("#CheckBoxId").on('ifChanged', function () {
                alert($(this).val());
            });
$('#checkbox1').click(function() {
    if($(this).is(":checked")) {
        var returnVal = confirm("Are you sure?");
        $(this).attr("checked", returnVal);
    }
    $('#textbox1').val($(this).is(':checked')); 
});


<div id="check">
    <input type="checkbox" id="checkbox1" />
    <input type="text" id="textbox1" />
</div>

删除change事件,改为更改单击事件中文本框的值。不是返回confirm的结果,而是在一个var中捕获它。如果它为真,则更改值。然后返回var。

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 " />