我试图从 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);
});
});
关于jquery - 如何在 Jquery 中使用类获取和放置这些特定字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58556352/