代码之家  ›  专栏  ›  技术社区  ›  Ahmad Farid

如何从javascript访问HTML文本框?

  •  7
  • Ahmad Farid  · 技术社区  · 15 年前

    如何通过javascript函数访问HTML文本框?

    5 回复  |  直到 9 年前
        1
  •  10
  •   Rich    15 年前

    设置文本框的ID属性并使用document.getElementByID()函数…示例如下:

    <html>
    <head>
    <script type="text/javascript">
    
    function doSomethingWithTextBox()
    {
      var textBox = document.getElementById('TEXTBOX_ID');
      // do something with it ...
    
    }
    
    </script>
    </head>
    
    <body>
    
    <input type="text" id="TEXTBOX_ID">
    
    </body>
    </html>
    
        2
  •  6
  •   Jonathon Oates    15 年前

    很简单,试试这个:

    <!doctype html>
    <html>
        <head>
            …
        </head>
    <body>
        <form>
            <input id="textbox" type="text" />
        </form>
        <script>
            var textboxValue = document.getElementById("textbox").value;
        </script>
    </body>
    

    变量 textboxValue 等于您在文本框中键入的内容。

    请记住,如果编写得如此简单,则必须将脚本放在文本框之后( input field)出现在HTML中,否则当第一次加载页面时,您会得到一个错误,因为脚本正在查找 输入 尚未由浏览器创建的字段。

    希望这有帮助!

        3
  •  5
  •   tomsseisums    15 年前

    给你的文本框一个 id 属性,然后用 document.getElementById('<textbox id>') .

        4
  •  5
  •   Ivo Wetzel    15 年前

    首先,您需要能够获取对文本框的DOM(文档对象模型)引用:

    <input type="text" id="mytextbox" value="Hello World!" />
    

    注意 id 属性,文本框现在具有ID mytextbox .

    下一步是获取javascript中的引用:

    var textbox = document.getElementById('mytextbox'); // assign the DOM element reference to the variable "textbox"
    

    这将通过它的 身份证件 属性。请注意,这些ID必须是唯一的,因此不能有两个具有相同ID的文本框。

    现在,最后一步是检索文本框的值:

    alert(textbox.value); // alert the contents of the textbox to the user
    

    这个 value 属性包含文本框的内容,就这样!

    要获得更多参考,您可能需要在MDC上查看一些资料:
    GetElementByID Reference
    Input Element Reference
    A general overview of the DOM

        5
  •  4
  •   Yishai Landau    15 年前

    document.getElementByID('textbox id').value 或 document.formname.textbox名称.value

    推荐文章