javascript - How to add an option to a html select, from input received from the user -


i have select client names populated sql database, part works fine, necessary add new client. want button displays popup user can provide new client name , have added select new option. below relevant code have tried. problem when either button pressed on prompt causes form submit , reloads page. 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 select created in php sql database edit: here code $dropdown3:

$clients = array(); $result = mysqli_query($link, "select name 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 final working code button requests user input , adds option select (as hidden field post purposes can added 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> 

Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -