$(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"/>
Here .change()
updates the textbox value with the checkbox status.
(在此.change()
使用复选框状态更新文本框值。)
.click()
to confirm the action on uncheck. (我使用.click()
来确认取消选中的操作。)
.change()
fires before confirmation. (如果用户选择“取消”,则复选标记会恢复,但是.change()
在确认之前会触发。)
This leaves things in an inconsistent state and the textbox says false when the checkbox is checked.
(这会使状态处于不一致状态,并且选中复选框时文本框会显示false。)
How can I deal with the cancellation and keep textbox value consistent with the check state?
(如何处理取消并保持文本框值与检查状态一致?)
ask by Professor Chaos translate from so