【发布时间】:2010-09-12 12:39:51
【问题描述】:
我想做的事:
- 我们在页面上有一个输入
- 我们按下“添加”按钮,然后在第一个输入之后添加另一个输入
- 在提交时,我们获取它们的所有值并将它们添加到一个数组中。
如何在页面上添加额外的输入(使用 jquery),然后在 php 中获取它们的内容?
【问题讨论】:
-
请定义“输入”。目前尚不清楚“输入”代表什么
标签: php javascript jquery input
我想做的事:
如何在页面上添加额外的输入(使用 jquery),然后在 php 中获取它们的内容?
【问题讨论】:
标签: php javascript jquery input
您不需要将输入显式添加到数组中。如果正确命名输入字段,PHP 会自动将它们解析为数组。
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>jQuery dynamic input sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
// Input adding function
function addInput() {
$('#inputs').append('<p><input type="text" name="input[]"></p>');
}
// Event handler and the first input
$(document).ready(function () {
$('#adder').click(addInput);
addInput();
});
</script>
</head>
<body>
<form id="form" method="post" action="jquery.php">
<a id="adder" href="#">Add Input</a>
<div id="inputs">
</div>
<input type="submit" />
</form>
</body>
</html>
PHP
foreach ($_POST['input'] as $key => $value) {
echo "$key $value";
}
【讨论】:
也许这会起作用(如果我正确理解问题)
$('#add').click(function(){
$(this).before('<input name="array[]"/>');
});
和我的php
<?php
if (isset($_GET['array'])) {
for ($i=0; $i<count($_GET['array']); $i++) {
echo "array[$i] -> {$_GET['array'][$i]}";
}
}
?>
【讨论】:
我已经发布了这个类似的问题,虽然这个问题只处理一个被克隆的输入,而不是多个输入。所以基本上,你的 HTML 应该是这样的:
<form id="my_form">
<input name="my_input[1]" id="my_input[1]">
</form>
<a href="#" id="add_input">Add one more</a>
它的 jQuery 看起来像这样:
$("#add_input").click(function(event) {
// Get the number of current inputs and set the new count ...
var inputCount = parseInt($("input[id^=my_input]").size());
var newInputCount = inputCount++;
// ... then create new clone based on the first input ...
var newInput = $("#my_input[1]").clone();
// .. and do the cleanup, make sure it has
// an unique ID and name for server-side parsing
newInput.attr('id', 'my_input[' + newInputCount + ']').attr('name', 'my_input[' + newInputCount + ']').val('');
// .. and finally insert it after the last fieldset
newInput.insertAfter("#my_input[" + inputCount + "]");
event.preventDefault();
});
然后,在 PHP 端,$_POST['my_input'] 将是一个包含所有添加字段值的数组,例如,使用 foreach() 很容易遍历它们。
希望这会有所帮助!
【讨论】: