[英]How to make a dynamic drop-down menu with php in javascript?
我试图用JavaScript中的php元素创建一个包含动态内容的下拉菜单,但是当我单击按钮add item时,什么也没发生。 php中的元素存储在$item[]
<script>
function addInput()
{
var table = document.getElementById("item");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "<select name="i1[]">
<?php
echo "<option selected disabled>Choose Item Code</option>";
$i=0;
while(!empty($item[$i]))
{
echo "<option value=".$item[$i].">".$item[$i]."</option>";
$i++;
}
?></select>";
cell2.innerHTML = "<input type='text' name='q1[]' size=10>";
cell3.innerHTML = "<input type='text' name='p1[]' size=10>";
}
</script>
您需要引用用PHP回显的代码,因为它将被视为javascript代码并以javascript代码执行,而不是作为应分配给innerHTML
属性的字符串引号执行。
此外,您应连接选项。
最好使用PHP变量构建选择,在其中添加所有选项,然后将其分配给单元innerHTML
function addInput()
{
var table = document.getElementById("item");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
<?php
$i=0;
$select = "<select name='i1[]'";
$options = "<option selected disabled>Choose Item Code</option>";
while(!empty($item[$i]))
{
$options .= "<option value=".$item[$i].">".$item[$i]."</option>";
$i++;
}
$select .= $options . "</select>";
?>
cell1.innerHTML = "<?php echo $select;?>";
cell2.innerHTML = "<input type='text' name='q1[]' size=10>";
cell3.innerHTML = "<input type='text' name='p1[]' size=10>";
}
您应该在PHP生成的每一行之后添加“ +”符号
function addInput()
{
var table = document.getElementById("item");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = ""+
"<select name='i1[]'>"+
<?php
echo "'<option selected disabled>Choose Item Code</option>'+";
$i=0;
while(!empty($item[$i]))
{
echo "'<option value=".$item[$i].">".$item[$i]."</option>'+";
$i++;
}
?>
"</select>";
cell2.innerHTML = "<input type='text' name='q1[]' size=10>";
cell3.innerHTML = "<input type='text' name='p1[]' size=10>";
}
像这样使用它:
<script>
function addInput()
{
var table = document.getElementById("item");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<select name="i1[]">
<?php
echo "<option selected disabled>Choose Item Code</option>";
$i=0;
while(!empty($item[$i]))
{
echo "<option value=".$item[$i].">".$item[$i]."</option>";
$i++;
}
?></select>';
cell2.innerHTML = "<input type='text' name='q1[]' size=10>";
cell3.innerHTML = "<input type='text' name='p1[]' size=10>";
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.