【问题标题】:Auto-Populate text field from drop-down selection in dynamically added rows从动态添加的行中的下拉选择中自动填充文本字段
【发布时间】:2014-10-29 12:13:14
【问题描述】:

我有一个表单,用户可以在其中动态添加行。在每一行中都有一个产品下拉菜单,应该自动填充一个文本字段,其中包含与所选产品相关的价格。这适用于第一行,但不适用于动态添加的行。产品名称仍在从 mysql 数据库中提取到下拉列表中,但在选择时不会自动填充文本字段。任何帮助,将不胜感激!

编辑:我添加了以下部分,我认为这将使整个工作正常进行,我只需要弄清楚如何将 i 变量附加到名称或 id 或类,然后我就可以进行自动填充代码包括 price[i] 和 product[i]... 我认为这将使它适用于每个动态添加的行。现在有什么想法吗?

for(var i=0;i<$('.orderform tr').length;i++)
{   
}

结束编辑

自动填充代码:

<script>

$(function() {  
$('select[name="product[]"]').change(function()
    {
         $('#price').val($('select[name="product[]"] option:selected').data('price'));
    });
  });
</script>

添加行代码:

<script>
$(document).ready(function(){
     //This line clones the row inside the '.row' class and transforms it to plain html.
     var clonedRow = $('.row').clone().html();

     //This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
     var appendRow = '<tr class = "row">' + clonedRow + '</tr>';  

 $('#btnAddMore').click(function(){
      //this line get's the last row and appends the appendRow when it finds the correct row.
      $('.orderForm tr:last').after(appendRow);
      for(var i=0;i<$('.orderform tr').length;i++)
{

}
});
</script>

HTML/PHP:

<table class="orderForm" id="orderForm" width="100%">
        <tr class="row">    
        <td>
       <div class="pure-control-group">
            <label>Product or Service</label><select name="product[]" id="product">
            <option value=""></option>
            <?php while($productRow = mysql_fetch_assoc($productResult)){?>
                  <option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option>
                            <?php } ?>
                      </select>

     </div>
     <div class="pure-control-group">

       <label>Price</label><input type="text" id="price" name="price[]">
       </div>
       <input type="button" class="deleteThisRow" id="deleteThisRow"  value="Delete"/>
       </td>
       </tr>
       </table>
       <input type="button" id="btnAddMore"  value="Add Product or Service" class="pure-button"/>

【问题讨论】:

    标签: php jquery mysql custom-data-attribute


    【解决方案1】:

    .clone() 默认情况下不会克隆事件处理程序。您可以使用.clone(true).appendTo(".orderForm");.clone() 函数的 true 参数也会复制值和事件。

    【讨论】:

    • 对不起,我对 jquery 知之甚少。你能再解释一下吗?我不知道该放在哪里。
    猜你喜欢
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-16
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多