登录  /  注册
首页 > web前端 > js教程 > 正文

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

php中文网
发布: 2016-06-01 09:55:01
原创
2131人浏览过

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

使用方法:

<code class="language-javascript">document.pref.color.value;//pref表示form表单的name,color是表单中元素的名称。</code>
登录后复制

实例:

<code class="language-html">

    <script language="JavaScript">
    function showColor(){
      var color = document.pref.color.value;
      console.log("Your favorite color is: " + color);
    }
    </script><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>

</code>
登录后复制

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

 

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

使用方法:

<code class="language-javascript">document.pref.elements[0].value //表示name为pref表单中第一个元素的值</code>
登录后复制

实例:

<code class="language-html">

    <script language="JavaScript">
    function showCar(){
      var car = document.pref.elements[0].value;
      console.log("Your favorite car is: " + car);
    }
    </script><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>

</code>
登录后复制

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

 

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

<code class="language-javascript">document.getElementById("id").value;</code>
登录后复制

实例:

<code class="language-html">
    
    <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>
    
</code>
登录后复制

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

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

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号