javascript 获取表单元素的几种方法

时间:2015-12-15
在实例开发过程中,我们经常会获取表单里的元素。本文章向大家讲解js中获取表单元素的几种方法。需要的码农可以参考一下。

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

使用方法:

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

实例:

<HTML>
<HEAD>
    <SCRIPT LANGUAGE="JavaScript">
    function showColor(){
      var color = document.pref.color.value;
      console.log("Your favorite color is: " + color);
    }
    </SCRIPT>
    </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" onClick="showCar(this.form)">
    <BR>
    Enter your favorite color:
      <INPUT TYPE="text" NAME="color" SIZE=15>
      <INPUT TYPE="BUTTON" NAME="colorButton" VALUE="Show Color" onClick="showColor(this.form)">
    </FORM>
</BODY>
</HTML>

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

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

使用方法:

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

实例:

<HTML>
<HEAD>
    <SCRIPT LANGUAGE="JavaScript">
    function showCar(){
      var car = document.pref.elements[0].value;
      console.log("Your favorite car is: " + car);
    }
    </SCRIPT>
    </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" onClick="showCar(this.form)">
    <BR>
    Enter your favorite color:
      <INPUT TYPE="text" NAME="color" SIZE=15>
      <INPUT TYPE="BUTTON" NAME="colorButton" VALUE="Show Color" onClick="showColor(this.form)">
    </FORM>
</BODY>
</HTML>

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

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

document.getElementById("id").value;

实例:

<html>
    <body>
    <script language="JavaScript">
    function getName(){
         var textName = document.getElementById("text_id").value;
         console.log("The textbox name is: " + textName);
    }
    </script>
    <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" onClick = getName()>
    </form>
    </body>
</html>

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

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