jquery - 如何在 Jquery 中使用类获取和放置这些特定字段的值

标签 jquery html

我试图从 2 个输入标签获取值,然后将它们相乘并将结果放入第三个输入标签中。

我成功地从输入标签中获取了值,但问题是我无法获取特定值。我需要使用类,因为我的主要目的是使用 foreach 循环获取购物车项目。我尝试使用 $(this) 关键字但失败了。

HTML:

price :<input type="text" class="inp" value=45>
quantity: <input type="text" class="inp-text" placeholder="enter a number" >
total:<input type="text" class="result" placeholder="result"><br><br>

price :<input type="text" class="inp" value=10>
quantity: <input type="text" class="inp-text" placeholder="enter a number" >
total:<input type="text" class="result" placeholder="result"><br><br>

price :<input type="text" class="inp" value=29>
quantity: <input type="text" class="inp-text" placeholder="enter a number" >
total:<input type="text" class="result" placeholder="result"><br><br>

Jquery

$(".inp-text").keyup(function() {
    console.log("key action");
    var key1 = $(this).val();
    // I want the value of this specific input class .inp and .inp-text
    $(".inp").attr("value", function() {
        var key2 = $(this).val();
        console.log(key1);
        console.log(key2);
        // multiply those values and then display it in result class
        var ress = key1 * key2;
        $(".result").val(ress);
    });
});

我想在结果字段中显示价格和数量的乘积。 例如。将第二行的输入更改为 5 后,它应该在结果列中生成 50。

10 * 5 = 50

最佳答案

您需要使用该元素相对于具有相同类的其他元素的索引(使用索引函数中的选择器)。

var index = $(this).index(".inp-text");

这个 fiddle 中的代码可以解决这个问题:

$(".inp-text").keyup(function() {
    console.log("key action");
    var index = $(this).index(".inp-text");
    var key1 = $(this).val();
    // I want the value of this specific input class .inp and .inp-text
    $(".inp:eq("+index+")").attr("value", function() {
        var key2 = $(this).val();
        console.log(key1);
        console.log(key2);
        // multiply those values and then display it in result class
        var ress = key1 * key2;
        $(".result:eq("+index+")").val(ress);
    });
});

https://jsfiddle.net/52Lvmtdr/

关于jquery - 如何在 Jquery 中使用类获取和放置这些特定字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556352/

相关文章:

javascript - intro.js 是如何工作的?

jquery - 随机显示(洗牌)div

javascript - 创建多个容器并修改它们的 div

javascript - 根据除第一个选项选择之外的所有选项更改 css

javascript - 如何在没有javascript的情况下检测屏幕分辨率?

html - CSS - flex 问题

PHP/Curl/Wordpress 在不刷新页面的情况下发布数据,curl 不工作

Javascript - 将数组结果过滤到下拉列表中

javascript - 缩放 div 的按钮(包含图像和 Canvas )

html - 如何在 CSS 中将图像与纯色混合?