【问题标题】:Add Multiple Levels of Input Fields添加多级输入字段
【发布时间】:2015-10-17 13:07:45
【问题描述】:

我有一个产品页面,会输入成本,数量,取2的产品后吐出成本。

我已经在http://jsfiddle.net/61tch8md/ 找到了大部分(我相信)但我遇到的问题是用户可以添加多行,每行只需要添加该行上字段的数量和成本.现在当我添加额外的行时,第一行将控制所有行的价格。

HTML

<table class="order-details">
    <tbody>
    <tr>
        <td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description 1" name="product-1-description" /></td>
        <td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity 1" name="product-1-quantity" /></td>
        <td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price 1" name="product-1-price"/></td>
        <td><span class="wei-price-total"></span></td>
        <td> </td>
    </tr>
    </tbody>
</table>

<div class="wei-add-service"><a href="#" class="button-secondary wei-add-service-button">Add Item</a></div>

JavaScript / Jquery

jQuery( "tr" )
  .keyup(function() {
    var value = jQuery( ".unit-price" ).val();
    var value2 = jQuery( ".quantity" ).val();
    var total = value * value2;

    jQuery( ".wei-price-total" ).text( total );
  })
  .keyup()

var counter = 2;
jQuery('a.wei-add-service-button').click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery('<tr><td><input type="text" value="" placeholder="Description of Work" class="wei-add-field description" name="product-' + 
        counter + '-description" /></td><td><input type="text" value="" placeholder="QTY" class="wei-add-field quantity" name="product-' + 
        counter + '-quantity" /></td><td><span class="wei-price">$</span><input type="text" value="" placeholder="Unit Price" class="wei-add-field unit-price" name="product-' + 
        counter + '-price"/></td><td><span class="wei-price-total">$49.99</span></td><td><a href="#" class="remove">remove</a></td></tr>');
    jQuery('table.order-details').append(newRow);
});


jQuery('table.order-details').on('click','tr a',function(e){
 e.preventDefault();
jQuery(this).parents('tr').remove();
});

提前致谢。

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    更改您的代码,使其选择keyup 发生所在行中的输入。

    jQuery('table.order-details').on("keyup", "tr", function() {
        var row = jQuery(this);
        var value = jQuery( ".unit-price", row ).val();
        var value2 = jQuery( ".quantity", row ).val();
        var total = value * value2;
    
        jQuery( ".wei-price-total", row ).text( total );
      });
    

    【讨论】:

    • 我更新了,现在只编辑第一行。当我添加其他行时,它们根本不会更新jsfiddle.net/61tch8md/1
    • 您需要使用事件委托将处理程序绑定到动态添加的行。就像您对删除行的函数所做的那样。我已经更新了答案以显示如何编写代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多