这是我的表单元素。
<select id="state" name="state" style="width: 212px;">
<option value="nsw">New South Wales</option>
<option value="qld">Queensland</option>
<option value="vic">Victoria</option>
<option value="nt">Northern Territory</option>
<option value="tas">Tasmania</option>
<option value="sa">South Australia</option>
<option value="wa">Western Australia</option>
<option value="act">Australian Capital Territory</option>
<option value="notinoz">Not in Australia</option>
</select>
如果用户在上面的选项中选择“不在澳大利亚”,我想要做的就是添加另一个选择框元素。 我真的追求最干净最轻的代码。
我假设我们创建一个div并设置可见性:隐藏但不确定如何触发它。
答案 0 :(得分:9)
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#state").change(function() {
// foo is the id of the other select box
if ($(this).val() != "notinoz") {
$("#foo").show();
}else{
$("#foo").hide();
}
});
});
</script>
</head>
<body>
<p>
<select id="state" name="state" style="width: 212px;">
<option value="nsw">New South Wales</option>
<option value="qld">Queensland</option>
<option value="vic">Victoria</option>
<option value="nt">Northern Territory</option>
<option value="tas">Tasmania</option>
<option value="sa">South Australia</option>
<option value="wa">Western Australia</option>
<option value="act">Australian Capital Territory</option>
<option value="notinoz">Not in Australia</option>
</select>
</p>
<p id="foo" style="display:none;">
<select style="width: 212px;>
<option value="item1">Item</option>
<option value="item2">Item</option>
<option value="item3">Item</option>
</select>
</p>
</body>
答案 1 :(得分:6)
这个怎么样? http://jsfiddle.net/JKqWf/4/
HTML
<select id="state" name="state" style="width: 212px;" onclick='test()'>
<option value="nsw">New South Wales</option>
<option value="qld">Queensland</option>
<option value="vic">Victoria</option>
<option value="nt">Northern Territory</option>
<option value="tas">Tasmania</option>
<option value="sa">South Australia</option>
<option value="wa">Western Australia</option>
<option value="act">Australian Capital Territory</option>
<option value="notinoz">Not in Australia</option>
</select>
<select id="extra" name="extra" style="display: none">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
JS
function test() {
if (document.getElementById('state').value == 'notinoz') {
document.getElementById('extra').style.display = 'block';
} else {
document.getElementById('extra').style.display = 'none';
}
}