javascript - 查询 : Product between 2 lists of inputs into a 3rd list

标签 javascript jquery

我在 jQuery 方面没有太多经验,我面临以下挑战

我有下表

<table>
    <thead>
        <tr>
            <td>Qty</td>
            <td>Description</td>
            <td>Unit Price</td>
            <td>Total Price</td>
        <tr>
    </thead>
    <tbody>
        <tr id="itemRow">
            <td><input type="text" name="quantity"/></td>
            <td><input type="text" name="description"/></td>
            <td><input type="text" name="unitPrice"/>/td>
            <td><input type="text" name="totalPrice"/></td>
        <tr>
    </tbody>
</table>

<input type="text" name="total"/>

此外,我可以根据需要多次克隆#itemRow,从而增加项目的数量。

想法是计算每一行的总价(按数量 * unitPrice)并将其分配给totalPrice。并将 totalPrice 的总和分配给 total

这是我正在使用的 javascript,但我收到一条错误消息“cantidades[i].val() is not a function”

function calculate(){

    var $total = $('#total');

    var $cantidades = $('input[name=quantity]')
    var $unitarios  = $('input[name=unitPrice]')
    var $totales = $('input[name=totalPrice]')

    var len = $cantidades.length;

    $total.val(0);

    for (var i = 0; i < len; i++){
        // calculate total for the row. ERROR HERE!
        $totales[i].val($cantidades[i].val() * $unitarios[i].val());

        // Accumulate total  
        $total.val($totalExento.val() + $totales[i].val());
    }
}

我错过了什么?我认为我没有从选择器中获取“jQuery 对象”,但我不确定是否热衷于这样做。

提前致谢!

最佳答案

这一行:var $cantidades = $('input[name=quantity]')检索一个无法像使用 $cantidades[i] 那样访问的 jQuery 实例.

像这样修复它:

var singleElementCantidades = $($cantidades[i]);
singleElementCantidades.val();

发生的事情是$('input[name=quantity]')检索作为 jQuery 实例的数组。当您使用 cantidades[i] 访问它的内容时,您不再管理 jQuery 实例,您正在访问其他没有 val 定义的东西。

关于javascript - 查询 : Product between 2 lists of inputs into a 3rd list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37580293/

相关文章:

javascript - Node js 中的日志文件重定向

javascript - 从字符串创建 react 组件

确认按钮中的javascript函数?

jquery - 特定类列表的第 n 个 child

javascript - 将唯一的时间跨度插入表中

javascript - Yeoman Mean.js 生成的自定义 AngularJS 指令不起作用

javascript - jQuery UI 可排序链接元素

javascript - 在图像中显示鼠标悬停工具提示

jquery - jqGrid "_search"参数始终为 false

javascript - ASP.NET 单选按钮 jQuery 处理