jQuery checkbox change and click event(jQuery复选框更改和单击事件)
问题描述
$(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="aHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvanF1ZXJ5LzMuMy4xL2pxdWVyeS5taW4uanM="></script>
<input type="checkbox" id="checkbox1"/><br />
<input type="text" id="textbox1"/>
这里 .change()
用复选框状态更新文本框值.我使用 .click()
来确认取消选中的操作.如果用户选择取消,复选标记将恢复,但 .change()
在确认之前触发.
Here .change()
updates the textbox value with the checkbox status. I use .click()
to confirm the action on uncheck. If the user selects cancel, the checkmark is restored but .change()
fires before confirmation.
这会使事情处于不一致的状态,并且在选中复选框时文本框会显示为 false.
This leaves things in an inconsistent state and the textbox says false when the checkbox is checked.
如何处理取消并保持文本框值与检查状态一致?
How can I deal with the cancellation and keep textbox value consistent with the check state?
推荐答案
在 JSFiddle 中测试并且确实如此您要什么.这种方法具有在单击与复选框关联的标签时触发的额外好处.
Tested in JSFiddle and does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.
更新答案:
$(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'));
});
});
这篇关于jQuery复选框更改和单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:jQuery复选框更改和单击事件
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01