【问题标题】:javascript dynamic Select from php sql queryjavascript动态从php sql查询中选择
【发布时间】:2021-07-10 15:16:01
【问题描述】:

关于在 javascript 中嵌入 php 有很多问题,我什至不想问这个问题,但我被困住了。

我有两件事是独立工作的,我基本上是在尝试将它们结合起来:

  • 通过php动态填写select选项
  • 通过javascript动态创建选择元素

我的 PHP 代码(我的第一次选择工作正常):

<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代码

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>";    
    }                   
  ?>

如果连续选择减少了基于先前选择的选项,则会获得奖励积分。 :)

感谢您的任何建议!

【问题讨论】:

    标签: javascript php embed


    【解决方案1】:

    简单的答案是: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)      
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      • 2019-08-17
      • 1970-01-01
      • 2017-09-13
      • 2019-04-04
      • 1970-01-01
      • 2019-06-10
      相关资源
      最近更新 更多