Home  >  Article  >  Web Front-end  >  javascript 获取表单元素的几种方法

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

WBOY
WBOYOriginal
2016-06-01 09:55:012184browse

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

使用方法:

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

实例:



    
    
    
    
Enter the name of your favorite car:
Enter your favorite color:

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

 

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

使用方法:

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

实例:



    
    
    
    
Enter the name of your favorite car:
Enter your favorite color:

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

 

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

document.getElementById("id").value;

实例:


    
    
    
This is a blank input textbox. Click on the button below to get the name of the textbox.


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

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:js 验证(判断)是否为网址Next article:js 解析xml实例