dsk95913 2018-07-13 06:44
浏览 51
已采纳

为什么document.getElementById输入类型=文本失败

Im trying to get data from form using getElementById. It works if i get from select form(like below), but why it fails when i try to get from textbox?

<select name="permission" id="permission" class="select2">
    <option value="rw">Read &amp; Write</option>
    <option value="r">Read Only</option>
</select>
<p id="demo"></p>

<script>
    var x= document.getElementById("permission").value;
    document.getElementById("demo").innerHTML = x;
</script>

If I change "permission" to "tenants" to get from below textbox, it doesn't show. I am confused ._.

<input type="text" id="tenants" name="tenants" class="form-control">
  • 写回答

6条回答 默认 最新

  • duanpie4763 2018-07-13 06:57
    关注
    <input type="text" id="tenants" name="tenants" class="form-control">
    

    If you want to get a value from this above code, use this.

    var x = document.getElementById("tenants").value;
    

    Looking at your original script

    <select name="permission" id="permission" class="select2">
        <option value="rw">Read &amp; Write</option>
        <option value="r">Read Only</option>
    </select>
    <p id="demo"></p>
    <script>
      var x= document.getElementById("permission").value;
      document.getElementById("demo").innerHTML = x;
    </script>
    

    This code only gets the value from select with an id permission and store it to p with an id demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?