我有一组单选按钮,我想取消后AJAX表单提交使用jQuery。我有以下功能:
function clearForm(){
$('#frm input[type="text"]').each(function(){
$(this).val("");
});
$('#frm input[type="radio":checked]').each(function(){
$(this).checked = false;
});
}
在这个函数的帮助下,我可以清除文本框中的值,但我不能清除单选按钮的值。
顺便说一下,我还尝试了$(this).val("");但这并没有起作用。
谢谢帕特里克,你让我今天很开心!你必须使用鼠标下键。不过,我已经改进了代码,以便您可以处理一组单选按钮。
//We need to bind click handler as well
//as FF sets button checked after mousedown, but before click
$('input:radio').bind('click mousedown', (function() {
//Capture radio button status within its handler scope,
//so we do not use any global vars and every radio button keeps its own status.
//This required to uncheck them later.
//We need to store status separately as browser updates checked status before click handler called,
//so radio button will always be checked.
var isChecked;
return function(event) {
//console.log(event.type + ": " + this.checked);
if(event.type == 'click') {
//console.log(isChecked);
if(isChecked) {
//Uncheck and update status
isChecked = this.checked = false;
} else {
//Update status
//Browser will check the button by itself
isChecked = true;
//Do something else if radio button selected
/*
if(this.value == 'somevalue') {
doSomething();
} else {
doSomethingElse();
}
*/
}
} else {
//Get the right status before browser sets it
//We need to use onmousedown event here, as it is the only cross-browser compatible event for radio buttons
isChecked = this.checked;
}
}})());