我有一个带有选项a,b和其他选项的单选按钮组。如果用户选择“其他”,则允许用户在文本字段中输入他们自己的值。 HTML:
<input type="radio" name="choice" id="a" value="a"/><label for="a">a</label><div></div>
<input type="radio" name="choice" id="b" value="b"/><label for="b">b</label><div></div>
<input type="radio" name="choice" id="other" value="other"/><label for="other">other </label><input type="text" id="otherText"/<div></div>
我正在学习jQuery,并且遇到了一个可能在这里有人可以阐明的行为。默认情况下,文本字段处于禁用状态,仅在用户单击“其他”时启用。我对这个文本域有一个模糊。我的代码:
$(document).ready(function () {
$("input#otherText").attr("disabled", "disabled");
$("input:radio").click(function() {
var choice = $(this).val();
if(choice != "other") {
$("input#otherText").attr("disabled", "disabled");
}else {
$("input#otherText").removeAttr("disabled");
}
});
$("input#otherText").blur(function() {
// why is this true even when I select "a" or "b"?
console.log("Is other checked?: " + $("input#other").is(":checked"));
});
});
我的问题是:
console.log("Is other checked?: " + $("input#other").is(":checked"));
为什么即使我选择其他单选按钮(如“a”或“b”),上述内容也会始终显示为真? 我问的原因是我最终想要验证用户在其他文本字段中输入的内容,但仅在检查“其他”时才验证。但由于总是如此,即使用户在单选按钮组中选择了其他选项,我也将被迫进行评估。我想这是不可避免的,但是有办法解决这个问题吗?
谢谢。
答案 0 :(得分:1)
摆脱&& otherError
的检查,它没有被定义,根据你想要做的,它不需要。这是一个演示:http://jsfiddle.net/UZZny/
您的控制台将打印每次true
,因为只有在选中该收音机时才会启用该文本框,模糊事件会触发,然后您的选择将会改变。