如何从用户接收到的输入中为html选择添加一个选项


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数据库创建的select编辑:下面是$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>