我有各种带有表单字段的div。基于下拉列表,我需要它来显示与该值对应的div,并隐藏所有其他div。 (也许有一种更有效的方法来做到这一点,而不是加载所有的div并隐藏它们,我不确定)。
我现在拥有的是:
<select id="group" name="group">
<option></option>
<option value="8">Testing This Stuff</option>
<option value="9">Testing Other Stuff</option>
</select>
<div id="8" style="display:none;">**form fields**</div>
<div id="9" style="display:none;">**different form fields**</div>
当前,半工作的javascript:
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.selectedIndex;
document.getElementById(id).style.display = 'block';
}
}
</script>
我得到的是'id'是空的,所以我还没有能够超越那部分。
第2部分将隐藏旧div并显示新div(如果他们要更改所选的选项)。有什么建议吗?
解决方案:
<script type="text/javascript">
window.onload = function() {
var current;
var eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
</script>
<select id="materialsgroup" class="formInput" name="materialsgroup">
<option value=""></option>
<option value="groupid_8">Testing This Stuff</option>
<option value="groupid_9">Testing Other Stuff</option>
</select>
<div id="groupid_8">**form fields**</div>
<div id="groupid_9">**more form fields**</div>
要制作select和div,这就是我所做的:
foreach($groups as $key=>$value)
{
$valueItem = "groupid_".$value['group_id'];
$text = $value['title'];
$htmlString .= sprintf('<option value="%s">%s</option>', $valueItem, $text);
}
echo '<tr>
<td class="formLabelCell">Group</td>
<td class="formInputCell">
<select id="group" class="formInput" name="group">'.$htmlString.'</select></td></tr>';
foreach($groups as $gkey=>$gvalue)
{
echo '<div id=groupid_'.$groups[$gkey]['group_id'].' style="display:none;">';
//**Draw the form stuff here**
echo '</div>';
}
答案 0 :(得分:3)
尝试使用
var id = eSelect.value;
对于第二部分,如果你使用纯javascript(我的意思是,你没有使用像jQuery这样的javascript框架)也许一个好的解决方案是加载一个包含div ids的数组并迭代它,隐藏div! = eSelect.value
var arrDivs = new Array("1","2","3");
for (var i=0; i < arrDivs.length; i++) {
if (arrDivs[i] == eSelect.value)
document.getElementById(arrDivs[i]).style.display = 'block';
else
document.getElementById(arrDivs[i]).style.display = 'none';
}
答案 1 :(得分:0)
我自己是一个javascript新手,但是如何使用当前变量来显示哪个div显示(因此知道要隐藏哪个div)?
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}
答案 2 :(得分:0)
window.onload = function() {
var current, eSelect = document.getElementById('group');
eSelect.onchange = function() {
var id = eSelect.value;
if (current && current != id) {
document.getElementById(current).style.display = 'none'
}
document.getElementById(id).style.display = 'block';
current = id;
}
}