您好,我正在尝试使用文本框生成动态 div 并在其中删除按钮。在提交表单时,我想要所有动态生成的文本框值,如何为文本框元素分配唯一 ID。文本框的 ID / 名称应该是唯一的.. 才能正确获取所有值。请建议..
我的代码:
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic elements</TITLE>
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a textbox dynamically
var eleText = document.createElement("input");
eleText.setAttribute("type", "text");
eleText.setAttribute("name", 'textbox' + count);
eleText.setAttribute("id", "textbox");
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(eleText);
eleDiv.appendChild(eleBtn);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px"><INPUT type="text" name="txtData" /></div>
<input type="submit" value="Submit"/>
</form>