将表单中的数据存储到 Javascript 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12402101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Store Data From a form into a Javascript variable
提问by Richlewis
I am a newbie when it comes to javascript, I'm playing with different tutorials and trying to make my own simple things to get a better understanding of it all. Today's learning is all about passing parameters through a function. What I would like to do is have a user fill a form in, submit those answers to variables in javascript and then call a function via an onClick event which will then display all the data entered into the form.
我是 javascript 的新手,我正在玩不同的教程,并尝试制作我自己的简单东西以更好地理解这一切。今天的学习都是关于通过函数传递参数。我想做的是让用户填写表单,将这些答案提交给 javascript 中的变量,然后通过 onClick 事件调用一个函数,然后该函数将显示输入到表单中的所有数据。
Firstly I hope this makes sense and secondly I hope that its the correct use of javascript, Im just trying to get a better understanding of passing params to be honest.
首先,我希望这是有道理的,其次我希望它正确使用 javascript,老实说,我只是想更好地理解传递参数。
Could anyone advise any resources or point me in the right direction on where to get started with this small project
任何人都可以建议任何资源或为我指明从哪里开始这个小项目的正确方向
回答by AboQutiesh
回答by sv_in
form elements are select
, input
, textarea
.
表单元素是select
, input
, textarea
。
On form, add a submit event handler which does the following
在表单上,添加一个执行以下操作的提交事件处理程序
Using document.getElementsByTagName
method, you can get a array of all such elements in the form.
使用document.getElementsByTagName
方法,您可以在表单中获取所有此类元素的数组。
All these elements have a value
property which will return the current value in it. Using this, you can create a string will the current data when form is submitted.
所有这些元素都有一个value
属性,它将返回其中的当前值。使用它,您可以在提交表单时创建一个字符串来显示当前数据。
回答by Developer
In order to get values from textboxes/textarea/dropdown having unique ID, you can use
为了从具有唯一 ID 的文本框/文本区域/下拉列表中获取值,您可以使用
document.getElementBtId("IDOFTHECONTROL").value
If the input is DIV/SPAN, use innerHTML
如果输入是 DIV/SPAN,则使用 innerHTML
document.getElementBtId("IDOFTHECONTROL").innerHTML
回答by Vishal Suthar
Simplest way:
最简单的方法:
var javascriptvar = document.getElementById('CONTROL_ID').value;