简体   繁体   中英

javascript dynamic Select from php sql query

There are so many questions around embedding php in javascript that I hate to even ask this, but I'm stuck.

I have two things working independently and I'm essentially trying to combine them:

  • dynamically filling in select options through php
  • dynamically creating a select element through javascript

My PHP code (works fine for my first select):

<select id="select_employee" name="employee">
  <option disabled selected value>-- Select an employee --</option>
  <?php
    while( $row = sqlsrv_fetch_array( $d_Employees, SQLSRV_FETCH_ASSOC))
    {
      echo "<option class='o_employee " . $row['dept'] . "' value='" . $row['employee'] . "'>" . $row['employee'] . "</option>";    
    }                   
  ?>
</select>

javascript code to add additional selects

const t_select = document.createElement("select")
  t_select.setAttribute('id', 'select_employee'+cols)
  t_select.setAttribute('name', 'employee'+cols)

  //create default option for select
  var option = document.createElement("option")
  option.setAttribute('disabled', 'disabled')
  option.setAttribute('selected', 'selected')
  option.setAttribute('value', 'value')
  option.innerHTML = '-- Select an employee --'
  t_select.appendChild(option)

  //create dropdown via php - this is where I'm stuck
  var option = document.createElement("option")
  option.????? = <?php
    while( $row = sqlsrv_fetch_array( $d_Employees, SQLSRV_FETCH_ASSOC))
    {
      echo "<option class='o_employee " . $row['dept'] . "' value='" . $row['employee'] . "'>" . $row['employee'] . "</option>";    
    }                   
  ?>

Bonus points if the consecutive selects pare down the options based on prior selections. :)

Thanks for any suggestions!

The easy answer was: cloneNode

var t_select = document.createElement("select")
var source = document.getElementById('select_employee0')
t_select = source.cloneNode(true)
t_select.setAttribute('id', 'select_employee'+cols)
t_select.setAttribute('name', 'employee'+cols)      

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM