我的表单中有很多输入字段,每次字段更改时,序列化的表单数据都会发送到服务器。
现在我需要阻止一些复选框被选中(不能使用"disabled"属性,单击这些复选框时必须触发alert() )。
我尝试了绑定到click()事件,但看起来change()事件在click()之前被触发,序列化的数据被发送,就像选中了复选框一样。
现在我尝试使用mousedown()事件,但prop('checked', false)似乎不起作用,实际上产生了相反的效果- checked总是处于选中状态。
这是JsFiddle测试用例- http://jsfiddle.net/F8x2X/19/
那么,如何在change()事件之前取消选中复选框?
发布于 2012-02-25 21:58:28
您可以将一个类放在不应选中的复选框上,并在change事件中进行选中
Foo: <input type="checkbox" name="foo" class='notcheck' value="1" /><br/>
<div id="result"></div>
$(':input').change(function(e){
if($(this).hasClass('notcheck')){
alert('you can\'t check this !');
$(this).removeProp('checked');
return;
}
var data = $(':input').serialize();
var checked = '';
if ($(this).is(':checked')) {
checked = 'Yes';
} else {
checked = 'No';
}
$('#result').append('Checked: ' + checked + '; Serialized: ' + data + '<br/>');
});在这里拉小提琴http://jsfiddle.net/nicolapeluchetti/F8x2X/20/
发布于 2019-03-11 18:17:35
如果用户确定要取消选中某个复选框,也可以使用confirm与用户进行确认,例如:
$('input.record_age').on('change', function(e) {
$this = $(this);
if(!$this.prop('checked')) { // only when unchecked
confirmed = confirm("Are you sure you want to stop recording age?");
if(!confirmed) { $this.prop('checked', true) } // if they press Cancel, change back to checked, otherwise leave as is.
}发布于 2012-02-25 22:21:41
我不确定我是否明白问题所在,但这就是问题所在:FIDDLE
var data = $(':input').prop('checked', false).serialize();https://stackoverflow.com/questions/9444557
复制相似问题