【发布时间】:2011-10-25 06:21:00
【问题描述】:
$(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() 来确认取消选中的操作。如果用户选择取消,复选标记会恢复,但.change()会在确认之前触发。
这会使事情处于不一致的状态,并且在选中复选框时文本框会显示为 false。
如何处理取消并保持文本框值与检查状态一致?
【问题讨论】:
-
它在 FF 和 chrome 中工作,并在 IE 8 中具有解释的行为。因此,请注意您需要在哪些浏览器中工作以及您在哪些浏览器中看到错误。跨度>
-
这不是最好的,但我相信它对我有用:http://jsfiddle.net/Skooljester/2Xxcn/。
标签: javascript jquery checkbox event-handling