帮助javascript onchange并显示/隐藏表格内容

时间:2010-09-24 20:58:12

标签: javascript

我想根据所选的选择值显示/隐藏td标记内的div。我无法显示标签文本,只显示文本框。有人可以帮我一把吗?

到目前为止,这是我的代码

<script>
function toggleOther(chosen){
if (chosen == 'oth') {
  document.myform.other.style.visibility = 'visible';
} else {
  document.myform.other.style.visibility = 'hidden';
  document.myform.other.value = '';
}
}
</script>
<form name="myform">
  <tr>
    <td>
      <select name="values" size="1" onchange="toggleOther( document.myform.values.options[ document.myform.values.selectedIndex ].value );">
      <option value=" " selected="selected"> </option>
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="oth">Other</option>
      </select>
    </td>
    <td>
      <div style="visibility:hidden">
        <label>adfdasfgsfg</label>
        <input type="text" name="other" value="" size="25" />
      </div>
    </td>
  </tr>
</form>

2 个答案:

答案 0 :(得分:1)

为元素指定一个id:

<div id="Other" style="visibility:hidden">

现在您可以在代码中轻松访问它:

document.getElementById('Other').style.visibility = 'visible';

编辑:

以下是包含更改,测试和工作的代码:

<script>
function toggleOther(chosen){
if (chosen == 'oth') {
  document.getElementById('Other').style.visibility = 'visible';
} else {
  document.getElementById('Other').style.visibility = 'hidden';
  document.myform.other.value = '';
}
}
</script>
<form name="myform">
  <tr>
    <td>
      <select name="values" size="1" onchange="toggleOther( document.myform.values.options[ 

document.myform.values.selectedIndex ].value );">
      <option value=" " selected="selected"> </option>
      <option value="name">Name</option>
      <option value="age">Age</option>
      <option value="oth">Other</option>
      </select>
    </td>
    <td>
      <div id="Other" style="visibility:hidden">
        <label>adfdasfgsfg</label>
        <input type="text" name="other" value="" size="25" />
      </div>
    </td>
  </tr>
</form>

答案 1 :(得分:0)

问题在于您已将<div>添加到hidden的可见性,但您的javascript仅显示您的输入。 (document.myform.other.style.visibility

要使其正常运作,只需将<div> id给出并显示并隐藏它:

// ... snip ...
function toggleOther(chosen){
var piece_to_hide = document.getElementById("otherValues");
if (chosen == 'oth') {
  piece_to_hide.style.display = 'block';
} else {
  piece_to_hide.style.display = 'none';
  document.myform.other.value = '';
}
}
// ... snip ...
  <div id="otherValues" style="display:none">
     <label>adfdasfgsfg</label>
     <input type="text" name="other" value="" size="25" />
  </div>