我有一个带有单选按钮和文本输入字段的表单:
<input type="radio" name="foo" value="bar">
<input id="baz" type="text">
...
文本输入字段具有keyup
与之关联的处理程序,当我开始在文本输入字段中输入内容时,该处理程序将检查单选按钮:
$('#baz').on('keyup', function() {
var bar = $('input[name="foo"][value="bar"]');
if (!bar.is(':checked')) {
bar.prop('checked', true);
}
});
形式也有一个“复位”按钮(带有id
的reset
)和下列click
处理程序:
$('#reset').on('click', function() {
$('input[type="radio"]').prop('checked', false);
$('input').val('');
});
问题:keyup
单击“重置”按钮后,输入字段的处理程序停止工作。
当我通过如下调用增加处理程序时console.log
:
$('#baz').on('keyup', function() {
var bar = $('input[name="foo"][value="bar"]');
if (!bar.is(':checked')) {
console.log('not checked');
bar.prop('checked', true);
console.log('New value for "checked" property: ' + bar.prop('checked'));
} else {
console.log('checked');
}
});
在单击“重置”按钮之前输入两个字符时,得到以下输出:
未检查
“已检查”属性的新值:true
已检查
单击“重置”按钮后输入两个字符时,输出如下所示:
未检查
“已检查”属性的新值:未定义
未检查
“已检查”属性的新值:未定义
checked
现在,单选按钮的属性undefined
为false
。(我假设这就是keyup
处理程序无法再对其进行设置的原因?)
我想了解这里发生了什么。keyup
单击“重置”后,如何修改代码以保留处理程序的功能?
我感觉好像缺少了一些明显的东西,但是到目前为止,我还无法在这里或其他地方为这个问题找到解决方案。
在#reset
事件处理程序中,将value
所有输入元素的设置为''
。
在keyup
处理程序中,您要使用name
和来选择单选按钮value
:
var bar = $('input[name="foo"][value="bar"]');
什么都不选择,因为您不再拥有 input[value="bar"]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句