[英]How to add an option to a html select, from input received from the user
我有一个带有从SQL数据库填充的客户端名称的选择,该部分工作正常,但有时需要添加一个新客户端。 所以我想要一个显示弹出窗口的按钮,用户可以在其中提供新的客户端名称,并将其作为新选项添加到选择中。 以下是我尝试过的相关代码。 问题是,当在提示上按下任一按钮时,它将导致表单提交并重新加载页面。 提前致谢。
<form action = "AddNewJob.php" method = "post">
...
<td><?php echo $dropdown3 ?><button onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (!client.equals("New client"))) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
}
}
</script></td>
...
<p><input type="hidden" id="newclientfield" value="" /></p>
<p align="center"><input type="submit" value="Submit" name="btnAdd"></p>
</form>
$ dropdown3是在PHP中从SQL数据库EDIT创建的选择:这是$ dropdown3的代码:
$Clients = array();
$result = mysqli_query($link, "SELECT Name FROM tblClients");
$i = 0;
$rownum = mysqli_num_rows($result);
while ($i < $rownum){
mysqli_data_seek($result, $i);
$row = mysqli_fetch_row($result);
$Clients[] = $row[0];
$i++;
}
$dropdown3 = "<select size=\"1\" name=\"Client\" id=\"Client\">";
$i = 0;
while($i < count($Clients)){
$dropdown3 .= "\r\n<option value = '" . $Clients[$i] . "'>" . $Clients[$i] . "</option>";
$i++;
}
$dropdown3 .= "\r\n</select>";
那部分工作正常。
这是请求用户输入然后将选项添加到选择中的按钮的最终工作代码(以及用于POST的隐藏字段,因此可以将其添加到数据库中)。
<button type="button" onclick="myFunction()">Add new client</button>
<script>
function myFunction() {
var client = prompt("Please enter client name", "New client");
if ((client != null) && (client != "New client")) {
var select = document.getElementById("Client");
select.options[select.options.length] = new Option(client, client);
document.getElementById('newclientfield').value = client;
select.selectedIndex=select.options.length - 1;
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.