我希望以动态生成输入文本的形式获取客户的电话号码。我做了这个
<HTML>
<HEAD>
<TITLE> get telephones </TITLE>
<SCRIPT language="javascript">
function add(type) {
//Create an input text dynamically.
if(typeof add.counter=='undefined')
{
add.counter=0;
}
add.counter++;
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", "");
element.setAttribute("name", type.concat(add.counter));
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
return add.counter;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM action="test1.php" method="post">
//here I think there is a problem
<INPUT type="button" value="Add" onclick="<?php echo "add('text')";?>"/>
<INPUT type="submit" value="Add" />
<span id="fooBar"> </span>
</FORM>
</BODY>
</HTML>
我想得到一个输入文本名称数组,或者计数器的最后一个值
答案 0 :(得分:0)
如果您将输入名称设置为“whatever []”,那么PHP将自动从输入数据创建数组,因此您只需更改
element.setAttribute("name", type.concat(add.counter));
// to
element.setAttribute("name", "thename[]");
并且你真的不想为它的名字重复使用元素类型 - 这是两个非常不同的东西,想出更好的东西
并删除所有计数器
答案 1 :(得分:0)
这里回答
<INPUT type="button" value="Add" onclick="add('text')"/>
<INPUT type="button" value="allPhoneNumbers" onclick="allPhoneNumbers()"/>
<script type="javascript">
function add(type)
{
if(typeof add.counter=='undefined')
{
add.counter=0;
}
add.counter++;
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", type);
element.setAttribute("value", "");
element.setAttribute("id", type.concat(add.counter));
element.setAttribute("name", 'phonenumbers[]');
var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);
return add.counter;
}
function allPhoneNumbers()
{
var phonenumbers=document.getElementsByName('phonenumbers[]');
for(var i=0;i<phonenumbers.length;i++)
{
alert(phonenumbers[i].value);
} }
</script>