php - 从动态添加的行中的下拉选择中自动填充文本字段

标签 php jquery mysql custom-data-attribute

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

编辑:我添加了以下部分,我认为这将使整个事情正常进行,我只需要弄清楚如何将 i 变量附加到名称或 id 或类,然后我就可以自动填充代码包括价格[i]和产品[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"/>

最佳答案

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

关于php - 从动态添加的行中的下拉选择中自动填充文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25670664/

相关文章:

php - Wordpress – 在阅读更多内容之前显示页面内容,无需使用循环

javascript - 在 jQuery 中使用命名函数作为 $.getJSON 的回调来满足 Facebook 请求签名需求

javascript - 将 HTML 输入值传递给 jQuery 表单值

javascript - 检查javascript和警报中的背景颜色

php - Doctrine2,映射 "inherited"表

php - 类别过滤器 IN 和电子商务 IN

PHPSpreadsheet - 如何使用自动迁移工具

javascript - 提交表单后显示 Bootstrap 模式

php - 如何在 PHP 中从 YouTube 数据 API 访问统计信息

mysql - 在 MySQL 中组织重复项