javascript - 添加多级输入字段

标签 javascript jquery

我有一个产品页面,会输入成本、数量,并在取出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();
});

提前致谢。

最佳答案

更改您的代码,以便它选择发生 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 );
  });

关于javascript - 添加多级输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33181221/

相关文章:

javascript - 通过表单中的隐藏输入字段传递当前页面 URL

javascript - 如何在 React 中渲染 50x50 的表格?

javascript - 内部服务器错误: Passing JavaScript object to C#

java - 如何使用 Java 和 Eclipse 在 HTML 网站上启动 Jquery 事件?

javascript - Bootstrap-slider.js 不会以编程方式触发 setValue 更改功能

javascript - 如何根据搜索关键字对字符串数组进行排序?

javascript - 页脚总是固定在页面 Bootstrap 的底部?

javascript - 如何在Jquery或Phonegap跨平台中获取IP地址

jquery - 滚动菜单中 jQuery stop() 中的奇怪效果/闪烁

javascript - 无法阻止用户返回到上一个登录页面