jQuery复选框更改并单击事件 [英] jQuery checkbox change and click event
问题描述
我有
< input type =checkboxid =checkbox1/> < br />
< input type =textid =textbox1/>
和
$(document).ready(function(){
//设置初始状态
$('#textbox1')。val($(this) )
$('#checkbox1')。change(function(){
$('#textbox1')。val($(this) )
$('#checkbox1')。click(function(){
if(!$(this).is(':checked' )){
return confirm(Are you sure?);
}
});
});
这里更改的事件将更新文本框值与复选框状态。我使用点击事件来确认取消选中的操作。如果用户选择取消,复选标记将被恢复,但更改甚至在确认之前触发,使事情处于不一致的状态(当勾选复选框时,文本框显示为错误)。如何处理取消并保持文本框值与检查状态一致?
我没有看到答案这匹配我的,所以我会发布。在 JSFiddle 中进行测试,并做你所要求的。这种方法有一个额外的好处是,当一个点击与复选框相关联的标签。
原始答案
$ (文件).ready(function(){
//设置初始状态
$('#textbox1')。val($(this).is(':checked'));
$('#checkbox1')。change(function(){
if($(this).is(:checked)){
var returnVal =你确定吗?);
$(this).attr(checked,returnVal);
}
$('#textbox1')。val($(this) (':checked'));
});
});
更新答案
$ b $ ($($)$($)$($)$($)$($) check(function(){
if(this.checked){
var returnVal = confirm(你确定吗? );
$(this).prop(checked,returnVal);
}
$('#textbox1')。val(this.checked);
} );
});
I have
<input type="checkbox" id="checkbox1" /> <br />
<input type="text" id="textbox1" />
and
$(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?");
}
});
});
Here the changed event updates the textbox value with the checkbox status. I use the click event to confirm the action on uncheck. If the user selects cancel, the check mark is restored but the change even fires before confirmation leaving things in a inconsistent state (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?
Well I don't see an answer that matches mine so I'll post this. 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.
Original Answer:
$(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'));
});
});
Updated Answer:
$(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);
});
});
这篇关于jQuery复选框更改并单击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!