第一种方法,通过元素的name获取

使用方法:

document.pref.color.value;//pref表示form表单的name,color是表单中元素的名称。

实例:

<HTML>
<HEAD>
    <  LANGUAGE=\" \">
    function showColor(){
      var color = document.pref.color.value;
      console.log(\"Your favorite color is: \" + color);
    }
    </ >
    </HEAD>
    <BODY>
    <FORM NAME=\"pref\" METHOD=POST>
    Enter the name of your favorite car:
      <INPUT TYPE=\"text\" NAME=\"car\" SIZE=25>
      <INPUT id=\"button1\" TYPE=\"BUTTON\" NAME=\"carButton\" VALUE=\"Show Car\"  =\"showCar(this.form)\">
    <BR>
    Enter your favorite color:
      <INPUT TYPE=\"text\" NAME=\"color\" SIZE=15>
      <INPUT TYPE=\"BUTTON\" NAME=\"colorButton\" VALUE=\"Show Color\"  =\"showColor(this.form)\">
    </FORM>
</BODY>
</HTML>

上面实例代码使用ocument.pref.color.value获取pref表单中name为color元素的值。

 

第二种方法:通过元素的index获取

使用方法:

document.pref.elements[0].value //表示name为pref表单中第一个元素的值

实例:

<HTML>
<HEAD>
    <  LANGUAGE=\" \">
    function showCar(){
      var car = document.pref.elements[0].value;
      console.log(\"Your favorite car is: \" + car);
    }
    </ >
    </HEAD>
    <BODY>
    <FORM NAME=\"pref\" METHOD=POST>
    Enter the name of your favorite car:
      <INPUT TYPE=\"text\" NAME=\"car\" SIZE=25>
      <INPUT id=\"button1\" TYPE=\"BUTTON\" NAME=\"carButton\" VALUE=\"Show Car\"  =\"showCar(this.form)\">
    <BR>
    Enter your favorite color:
      <INPUT TYPE=\"text\" NAME=\"color\" SIZE=15>
      <INPUT TYPE=\"BUTTON\" NAME=\"colorButton\" VALUE=\"Show Color\"  =\"showColor(this.form)\">
    </FORM>
</BODY>
</HTML>

此实例获取了表单中第一个元素的值,表单的第一个元素应该是name为car的input

 

第三种方法:通过元素的id获取

document.getElementById(\"id\").value;

实例:

<html>
    <body>
    <  language=\" \">
    function getName(){
         var textName = document.getElementById(\"text_id\").value;
         console.log(\"The textbox name is: \" + textName);
    }
    </ >
    <form name=\"form1\">
    This is a blank input textbox. Click on the button below to get the name of the textbox.
    <br>
    <input type=\"text\" id=\"text_id\" name=\"textbox1\" size=25>
    <br><br>
    <input type=\"button\" value=\"Get Name\"   = getName()>
    </form>
    </body>
</html>

使用document.getElementById("text_id")获取id为text_id的input.

注:本文章的实例代码均可复制到这里运行并查看结果,你不妨试一把。

收藏 打印