I have a select with client names that is populated from a SQL database, that part works fine, but occasionally it is necessary to add a new client. So I want a button that displays a popup where the user can provide the new client name and have it added to the select as a new option. Below is the relevant code that I have tried. The problem is that when either button is pressed on the prompt it causes the form to submit and reloads the page. Thanks in advance.
<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 is the select that is created in PHP from the SQL database EDIT: Here is the code for $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>";
That part works fine.
This is the final working code for the button that requests user input and then adds the option to the select (as well as a hidden field for POST purposes so it can be added to the database).
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.