如何使用select选项在JavaScript中生成n个输入文本框。我如何在PHP中获取变量。
下面是我的html表单
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
var numberOfElementsAdded;
var arrayOfInputs = new Array();
function addToDatabase(numberOfElementsAdded) {
numberOfElementsAdded = numberOfElementsAdded * numberOfElementsAdded;
var alltext = "";
for (var j = 1; j <= numberOfElementsAdded; j++) {
var tvalue = document.getElementsByName("text" + j)[0].value;
arrayOfInputs.push(tvalue);
alltext = alltext + tvalue + " ";
}
alert(alltext);
}
function add(type, num) {
numberOfElementsAdded = num;
//Create an input type dynamically.
var k = 0;
for (var j = 0; j < num; j++) {
for (var i = 0; i < 4; i++) {
var element = document.createElement("input");
k = k + 1;
//Assign different attributes to the element.
element.setAttribute("type", type + k);
element.setAttribute("id", type + k);
element.setAttribute("name", type + k);
element.setAttribute('width', '30');
element.setAttribute('border', '3px solid #FF0000');
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
}
var breakLoop = document.createElement('br')
foo.appendChild(breakLoop)
}
var element = document.createElement("input");
element.setAttribute("type", "button");
element.setAttribute("id", "Submit");
element.setAttribute("name", "Insert into database");
element.setAttribute("value", "Insert into database");
element.setAttribute("onclick", "addToDatabase(numberOfElementsAdded)");
var breakLoop = document.createElement('br')
foo.appendChild(breakLoop)
foo.appendChild(element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<H2>Dynamically add element in form.</H2>
<SELECT name="element">
<OPTION value="1">1</OPTION>
<OPTION value="2">2</OPTION>
<OPTION value="3">3</OPTION>
<OPTION value="4">4</OPTION>
<OPTION value="5">5</OPTION>
<OPTION value="6">6</OPTION>
<OPTION value="7">7</OPTION>
<OPTION value="8">8</OPTION>
<OPTION value="9">9</OPTION>
<OPTION value="10">10</OPTION>
</SELECT>
<INPUT type="button" value="Add" onclick="add('text',document.forms[0].element.value)"/>
<BR/>
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
它会生成文本框。但我想将文本框的值作为PHP变量获取。
答案 0 :(得分:0)
假设代码正确生成文本框,要获取PHP中的值,您必须修改它:
element.setAttribute("name", "Insert into database");
到
element.setAttribute("name", "myFieldName[]"); // with the [] brackets
然后在PHP中,你会这样:
$fields = $_POST['myFieldName'];
// make it into a single delimited field
$fields = implode('|', $fields);