javascript 通过一个表单提交多个输入并附加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22886631/
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
Submit multiple inputs through one form and append to array
提问by Arun Kalyanaraman
So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
所以我对 JavaScript 比较陌生,但我有编程经验。我有这个代码,它允许用户定义他们想要输入的地址数量,这样我就可以查询谷歌地图并找到地理中心。这样做的问题在于,他们必须在一页上输入字段数量,然后在下一页上提示他们使用那么多框,因此这看起来非常不专业。有什么方法可以只制作一个表单(包含一个条目所需的所有参数),然后在他们点击提交后,我将它附加到一个数组中,然后当他们确定他们有足够的地址时,他们点击了最终提交,然后我可以使用 PHP 调用处理数据吗?任何帮助都会很棒,但我是新手,所以我可能需要更详细的解释,抱歉。再次感谢!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
TL;DR:我想创建一个单一的条目字段,当点击提交时,页面不会刷新或重定向到新页面并将数据条目附加到数组。从那里用户可以输入一个新的输入,这个输入也将被附加到数组中,直到用户决定不再需要输入,此时他们将单击最终提交,允许我处理数据。
Here is the code I have so far:
这是我到目前为止的代码:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
获取数据文件
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
回答by Johny
Here is code:
这是代码:
EDIT:I rewrite the code, so you can also delete each address
编辑:我重写了代码,所以你也可以删除每个地址
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
表单提交后,您可以循环访问这样的地址:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
希望这有帮助!:)
回答by Omer Arshad
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddleto see what I mean.
通常我做这种事情的方式是让用户能够在客户端级别添加许多输入字段,并在提交表单时将它们全部发送到一个数组中。我相信这更专业。试试这个JSFiddle看看我的意思。
<input type="text" name="address[]" />
回答by MamaWalter
if you want to POST
dynamic value in a form you can do it like this:
如果你想POST
在一个表单中动态值,你可以这样做:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]"
.
and in your PHP you get an array:
因此,在您的情况下,您可以使用具有相同名称的 javascript 或 jquery 添加新字段name="adress[]"
。在你的 PHP 中你得到一个数组:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
回答by Wilmer
To process an array of inputs you can use the following convention:
要处理输入数组,您可以使用以下约定:
HTML: simply add square brackets to the name attribute
HTML:只需在 name 属性中添加方括号
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
PHP:Post 返回一个数组
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize()
will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
JAVASCRIPT:$("#form1").serialize()
将检索所有输入数据作为名称=值对,即使是动态添加的输入。无需保留数组,您可以在最后处理所有数组。
回答by webeno
You don't need to create an array, $_POST
is actually doing it all for you already.
你不需要创建一个数组,$_POST
实际上已经为你做了这一切。
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the preventDefault
on the form)name
attributes of each input element that gets created.
因此,我建议您执行以下操作:使用 javascript(或 jQuery),保持按钮点击,但确保防止表单提交([编辑:您实际上不需要这个,就像按钮一样只是按钮,没有提交输入,表单无论如何都不会提交],并确保每次他们点击加号按钮或其他东西时附加另一个元素;确保增加preventDefault
在表单上使用)name
创建的每个输入元素的属性。
When the user then creates submit, use submit the form via js, then on your getdata.php
you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input
element has been added to the form.
当用户然后创建提交时,使用通过 js 提交表单,然后getdata.php
您可以简单地遍历所有值并以您想要的方式使用它们。您甚至可以通过计算新input
元素添加到表单的次数来知道确切的数字。
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
我会试着在一分钟内为你写一些东西,但如果我足够清楚,你也应该能够做到。
EDITED:So here is what I've come up with; give it a try and see if this is something for you.
编辑:所以这就是我想出的;试一试,看看这是否适合你。
This is how the form would look like:
这是表单的样子:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
这将是 js 代码:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
...然后getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}