javascript 从表单javascript传递变量值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13673549/
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
Pass variable value from form javascript
提问by Simon Carlson
Say I got a HTML form like below and want to pass the values in the textfields to JS variables.
假设我有一个如下所示的 HTML 表单,并且想要将文本字段中的值传递给 JS 变量。
<form name="testform" action="" method="?"
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
</form>
I've only passed values to variables in PHP before. When doing it in javascript, do I need a method? And the main question, how is it done?
我之前只在 PHP 中将值传递给变量。在 javascript 中执行此操作时,我需要一个方法吗?主要问题是,它是如何完成的?
采纳答案by Lowkase
Here are a couple of examples:
下面是几个例子:
Javascript:
Javascript:
document.getElementById('name_of_input_control_id').value;
jQuery:
jQuery:
$("#name_of_input_control_id").val();
Basically you are extracting the value of the input control out of the DOM using Javascript/jQuery.
基本上,您是使用 Javascript/jQuery 从 DOM 中提取输入控件的值。
回答by ffffff01
Try the following in your "submit":
在“提交”中尝试以下操作:
var input = $("#testfield1").val();
回答by Mik
the answers are all correct but you may face problems if you dont put your code into a document.ready function ... if your codeblock is above the html part you will not find any input field with the id, because in this moment it doesnt exist...
答案都是正确的,但是如果您不将代码放入 document.ready 函数中,您可能会遇到问题……如果您的代码块位于 html 部分之上,您将找不到任何带有 id 的输入字段,因为此时它没有存在...
document.addEventListener('DOMContentLoaded', function() {
var input = document.getElementById('name_of_input_control_id').value;
}, false);
jQuery
jQuery
jQuery(document).ready(function($){
var input = $("#name_of_input_control_id").val();
});
回答by lostsource
You don't really need a method
or an action
attribute if you're simply using the text fields in Javascript
如果您只是在 Javascript 中使用文本字段,则您实际上并不需要 amethod
或一个action
属性
Add a submit
button and an onsubmit
handler to the form like this,
像这样向表单添加一个submit
按钮和一个onsubmit
处理程序,
<form name="testform" onsubmit="return processForm(this)">
<input type="text" name="testfield1"/>
<input type="text" name="testfield2"/>
<input type="submit"/>
</form>
Then in your Javascript you could have this processForm
function
然后在您的 Javascript 中,您可以拥有此processForm
功能
function processForm(form) {
var inputs = form.getElementsByTagName("input");
// parse text field values into an object
var textValues = {};
for(var x = 0; x < inputs.length; x++) {
if(inputs[x].type != "text") {
// ignore anything which is NOT a text field
continue;
}
textValues[inputs[x].name] = inputs[x].value;
}
// textValues['testfield1'] contains value of first input
// textValues['testfield2'] contains value of second input
return false; // this causes form to NOT 'refresh' the page
}