如果用户在一个option value
字段中选择某个select
,那么如何创建文本字段hidden
,则不需要。这必须在提交表单之前完成吗?
例如,在以下选择字段中,用户选择选择value='a'
,然后该文本字段将如何隐藏:
<select name="form" id="aForm">
<option value="a">choice1</option>
<option value="b">choice2</option>
<option value="c">choice3</option>
</select>
<input type="text" style="width:285px" name="textField" id="textField"/>
答案 0 :(得分:4)
$("#aForm").on("change", function() {
if ($(this).val() == "a")
$("#textField").hide();
else
$("#textField").show();
});
这也是jsfiddle
我假设您将显示除了。
之外的任何其他值的文本字段如果您使用的是纯JavaScript而不是jQuery
function hideTF() {
var s = document.getElementById("aForm");
document.getElementById("textField").style.display
= (s.selectedIndex > 0 && s.options[s.selectedIndex] == 'a'
? "none" : "block");
}
var s = document.getElementById("aForm");
if (s.attachEvent)
s.attachEvent("onchange", hideTF);
else
s.addEventListener("change", hideTF, false);
答案 1 :(得分:2)
您可以使用以下变体:
var selection = aForm.selectedIndex,
field = document.getElementById('textField');
if ( selection === x ) {
field.style.display = "block"; // or visibility = "hidden"
}
这应该包含在.onchange
事件中。 aForm.selectedIndex
是所选的相应<option>
元素的索引。