[英]I need help getting Javascript to read an HTML form, and assign it to a specific array
I need help getting javascript to read an html input form, and assign the input to an array, or atleast what i think is an array....im not sure. 我需要获取JavaScript来读取html输入形式的帮助,并将输入分配给数组,或者至少我认为是数组....我不确定。
i want to take the data from an html form, and put it in here: 我想从html表单中获取数据,并将其放在此处:
var users = ['"This is a random qoute"-lastname,firstname."','"This is a random
qoute"-lastname,firstname."'];
is this possible? 这可能吗?
Check about jQuery.serializeArray 检查有关jQuery.serializeArray
Example: 例:
$('form').submit(function() {
var params = $(this).serializeArray();
console.log(params);
return false;
});
The console will show something like: 控制台将显示如下内容:
[
{
name: "input1Name",
value: "input1Value"
},
{
name: "input2Name",
value: "input2Value"
}
]
After your form submit you can access your params in objects, like: 提交表单后,您可以访问对象中的参数,例如:
Get all 得到所有
jQuery.each(params, function(objPosition, obj){
alert("name: " + obj.name + " Value: " + obj.value);
});
OR to get one ( in this case's the first one) 或 得到一个 (在本例中是第一个)
alert("name: " + params[0].name + " Value: " + params[0].value);
You can see it working here : http://jsfiddle.net/ricardolohmann/Jfu9H/ 您可以在这里看到它的工作原理 : http : //jsfiddle.net/ricardolohmann/Jfu9H/
If you want an array of the text input names and values, the following will do the job. 如果您想要一个由文本输入名称和值组成的数组,则将执行以下操作。 If you want to
如果你想
serialize a form for posting, that takes a little more code. 序列化表单以进行发布,这需要更多代码。
<script type="text/javascript">
function getInputs(form) {
var input, inputs = form.getElementsByTagName('input');
var result = [];
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
if (input.type == 'text') {
result.push(input.name + ': ' + input.value)
}
}
return result;
}
</script>
<form>
<table>
<tr>
<td>name<td><input type="text" name="userName">
<tr>
<td>age<td><input type="text" name="userAge">
<tr>
<td colspan="2"><input type="button" value="Show inputs"
onclick="alert(getInputs(this.form));">
</table>
</form>
Shows "userName: <value>, userAge: <value>"
显示
"userName: <value>, userAge: <value>"
You can do this nicely with jQuery.serialize() 您可以使用jQuery.serialize()很好地做到这一点
If you are not familiar with jQuery use this Tutorial to understand its basics. 如果您不熟悉jQuery,请使用本教程来了解其基础知识。 It's a Java Script Library.
这是一个Java脚本库。
Now you can work according to this example written by me. 现在您可以根据我写的这个示例进行工作。
it reads form element values into a string, 它将表单元素值读取为字符串,
var srt=$("form").serialize();
and split the resulted string from '&' sing to get the expected string array. 并从'&'sing中拆分结果字符串以获取预期的字符串数组。
var srtArray=srt.split('&');
result is something like this, 结果是这样的,
["text1=Lasantha", "dropDownList1=Single", "List1=Multiple1", "List1=Multiple3", "checkBox2=check2", "radioButton1=radio1"]
it is in the form of, 它的形式是
["name=value","name=value"....]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.