jQuery将输入值相乘并与另一个输入求和 [英] jQuery Multiply input value and sum with another input
问题描述
我一直在尝试使此相对简单的功能起作用,但不会起作用.它始终将数字输出为字符串,而不是将它们加在一起.
I've been trying to get this relatively simple function to work and it won't. It keeps outputting the numbers as a string instead of adding them together.
$('#FS-quantity-1').change(function() {
var subtotal = $("#HF-quantity").val()*2;
var sum = Number(subtotal)+$("#FS-quantity-1").val();
$("#sticker-quantity").val(sum);
});
这会将两个值一起输出为字符串,而不是将它们加在一起.还尝试了这个:
This outputs the 2 values together as a string instead of adding them together. Also tried this:
$('#FS-quantity-1').change(function() {
var subtotal = $("#HF-quantity").val()*2;
var sum = parseInt(subtotal)+$("#FS-quantity-1").val();
$("#sticker-quantity").val(sum);
});
那也不起作用.我还尝试将小计乘以1将其转换为整数.那没用.
And that didn't work either. I also tried multiplying subtotal by 1 to convert it to an integer. That didn't work.
有什么想法可以求出小计和#FS-quantity-1的val()求和为整数吗?
Any ideas how I can get subtotal and the val() of #FS-quantity-1 to sum as an integer?
推荐答案
使用:
var sum = subtotal + parseInt($("#FS-quantity-1").val(), 10);
由于用于分配它的乘法,因此您不必在subtotal
上使用Number
,因为它已经是一个数字.但是.val()
返回一个字符串,并且您需要将其转换为数字,因为如果两个参数中的任何一个都是字符串,则+
会执行串联操作.
You don't need to use Number
on subtotal
because it's already a number, due to the multiplication that was used to assign it. But .val()
returns a string, and you need to convert that to a number, because +
performs concatenation if either of the arguments is a string.
这篇关于jQuery将输入值相乘并与另一个输入求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!