我使用 Javascript
动态添加 textbox
以便用户在一个过程中添加更多项目。下面是添加 textboxes
的代码:
<script type="text/javascript">
var quantity = document.getElementById('quantity');
var item = document.getElementById('item');
var serial = document.getElementById('serial');
var property = document.getElementById('property');
document.getElementById('add').onclick = function () {
var input = document.createElement('input'),
div = document.createElement('div');
input.type = "text";
input.setAttribute("name", "quant");
div.appendChild(input);
quantity.appendChild(div);
var input2 = document.createElement('input'),
div2 = document.createElement('div');
input2.type = "text";
input2.setAttribute("name", "items");
div.appendChild(input2);
item.appendChild(div);
var input3 = document.createElement('input'),
div3 = document.createElement('div');
input3.type = "text";
input3.setAttribute("name", "serno");
div.appendChild(input3);
serial.appendChild(div);
var input4 = document.createElement('input'),
div4 = document.createElement('div');
input4.type = "text";
input4.setAttribute("name", "proper");
div.appendChild(input4);
property.appendChild(div);
};
</script>
当用户单击“添加文本”按钮时,将出现一组(四个文本框
)。我的问题是,即使用户单击并将数据输入到那些 textbox
中,它也只会插入一组数据(这是最后一组输入)。这是因为 textbox
的“名称”是相同的。如何插入这些多个数据?或者我如何为添加的 textbox
设置一个唯一的名称,以便将它们插入到数据库中?
最佳答案
您需要更改附加有 []
的名称。这将在表单提交时将一个数组传递给 PHP。
input.setAttribute("name", "quant[]");
要获取 PHP 中的值,
$quant_values = $_GET['quant']; // array of values
$value_one = $quant_values[0];
您将需要实现一个循环来遍历这些值。
关于javascript - 如何将动态添加的文本框插入MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20607405/