【问题标题】:Append / copy table row with a dropdown value from database in javascript / jQuery在javascript / jQuery中使用数据库中的下拉值附加/复制表行
【发布时间】:2020-05-31 05:20:56
【问题描述】:

我在表行中有一个来自数据库的下拉值,

<button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>
<table class="table" id="table">
      <thead>
        <tr>
          <th scope="col">Name</th>
        </tr>
      </thead>
      <tbody>
        <tr>
            <td>
            <select >
              <option selected="" disabled="">--Select Product Name--</option>
                <?php
                $con = new mysqli($host, $dbid, $dbpass, $dbname);
                $stmt = $con->prepare( "SELECT name FROM product ORDER BY name DESC" );
                $stmt->execute();
                $result = $stmt->get_result();
                $con->close();
                while($row = mysqli_fetch_assoc($result)) {
                  echo '<option value="'.$row["name"].'">'.$row["name"].'</option>';
                }
              ?>
            </select>
            </td>
        </tr>
        </tbody>
    </table>

如果我单击添加按钮,我想追加具有相同下拉列表的行而不再次进行数据库查询(对于下拉列表值)。 我已经让 jQuery 添加行

  $("#addbutton").click(function(){
    $('#table tr:last').after(' _??_ ');
  });

最好的方法是什么?

【问题讨论】:

    标签: javascript php html jquery forms


    【解决方案1】:

    您可以通过选择包含select 然后.clone() 它的&lt;tr&gt; 来实现,并使用.appendTo() 您可以添加到表中,这是一个有效的sn-p:

    $('#addbutton').click(function() {
      $('table tr:last-child').clone().appendTo($('table'))
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" class="btn btn-outline-primary" id="addbutton">Add Item</button>
    <table class="table" id="table">
        <thead>
            <tr>
                <th scope="col">Name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <select>
                        <option selected="" disabled="">--Select Product Name--</option>
                        <option selected="" disabled="">option1</option>
                        <option selected="" disabled="">option2</option>
                        <option selected="" disabled="">option3</option>
                        <option selected="" disabled="">option4</option>
                    </select>
                </td>
            </tr>
        </tbody>
    </table>

    【讨论】:

    • 哇,很好的答案,但在我的代码中,它也给了我复制标题。我已编辑为` var $last = $("#table tbody").find('tr:last'); $last.clone().appendTo($('table')) ` 并且它按预期工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2017-10-03
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2017-09-30
    相关资源
    最近更新 更多