更改文本字段数,具体取决于下拉列表选项

时间:2017-04-14 10:29:57

标签: javascript html textfield visibility

我在选择" id"之后尝试显示两个测试字段从下拉列表中。它设置为隐藏,我试图让它在" id"被选中。不幸的是它没有用。请帮忙!

<form>
            <input class="hidden" type="text" id="textField2">
            <input type="text" id="textField">

             <select id="select" name="selectData">
                    <option value="firstName">Name</option>
                    <option value="id">Id</option>
            </select>
            <input id="filter" type="button" value="Filter">

            <script>
                    var temp = document.getElementById("textField2").value;
                    if(document.getElementById("select")[0].value === "id"){
                            temp.style.visibility = "visible";
                    }else {
                            temp.style.visibility = "hidden";
                    }
            </script>
</form>

某处可能存在错误,或者可能还有其他(更好)的方法吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下解决方案:

<form>
  <script>
    function toggle() {
      var temp = document.getElementById("textField2");
    
      //check for selected option.
      if(document.getElementById("select").value === "id"){
        temp.style.visibility = "visible";
      } else {
        temp.style.visibility = "hidden";
      }
    }
  </script>
  <input class="hidden" type="text" id="textField2" style="visibility:hidden;">
  <input type="text" id="textField">
  
  <select id="select" name="selectData" onchange="toggle()">
    <option value="firstName">Name</option>
    <option value="id">Id</option>
  </select>
  
  <input id="filter" type="button" value="Filter">         
</form>