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

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


当前回答

给你

Html

<input id="ProductId_a183060c-1030-4037-ae57-0015be92da0e" type="checkbox" value="true">

JavaScript

<script>
    $(document).ready(function () {

      $('input[id^="ProductId_"]').click(function () {

        if ($(this).prop('checked')) {
           // do what you need here     
           alert("Checked");
        }
        else {
           // do what you need here         
           alert("Unchecked");
        }
      });

  });
</script>

其他回答

对我来说,这很有效:

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

Demo

使用mousedown

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

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

迟回答,但你也可以用on(“change”)

$(" #检查”)。On ('change', function() { Var checked = this。checked $('时间'). html (checked.toString ()) }); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="checkbox" id="check"> <span>检查我!< / span >