[英]Multiply Checkbox Value with Input Box Value - Jquery
I am currently struggling to get the value I return from a checkbox to multiply with the value in the input box with jQuery. 我目前正在努力从复选框中获取值,并使用jQuery与输入框中的值相乘。
I display a div when a checkbox is ticked to ask it for the quantity, thereafter I must multiply the quantity with the value of the checkbox. 当勾选复选框以询问数量时,我会显示一个div,此后我必须将数量乘以复选框的值。
Here is the current code: 这是当前的代码:
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
recalculateQty();
recalculateCheck();
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
if ($('#2').is(':checked')) {
$('#checked-2').show();
} else {
$('#checked-2').hide();
}
if ($('#3').is(':checked')) {
$('#checked-3').show();
} else {
$('#checked-3').hide();
}
});
function recalculateQty() {
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
recalculateCheck();
});
});
}
function recalculateCheck() {
var sum = 0;
$("input[type=checkbox]:checked").each(function () {
sum += parseInt($(this).val());
});
$('.qty').keyup(function () {
$('.qty').each(function () {
qty += parseInt(this.value, 10);
});
});
$('#total').val(sum * qty);
}
});
<input type="checkbox" id="1" value="30" name="1" />
<input type="checkbox" id="2" value="60" name="2" />
<input type="checkbox" id="3" value="90" name="3" />
<div style="display:none;" id="checked-1">
<input type="text" name="product_1_qty" id="product_1_qty" placeholder="Quantity" class=" qty" value="0" />
</div>
http://jsfiddle.net/isherwood/9vRtJ/1/ http://jsfiddle.net/isherwood/9vRtJ/1/
You are trying to set an element value with total
ID as a final result, but there is no such element in your html code. 您正在尝试使用total
ID设置元素值作为最终结果,但您的html代码中没有此类元素。
Just add this element in your html code (here i put another textbox): 只需在你的html代码中添加这个元素(这里我放了另一个文本框):
<input type="text" id='total'>
Check out the Live demo for your fix 查看您的修复的实时演示
Or you can use better coding:(Read the comments) - Working DEMO 或者你可以使用更好的编码:(阅读评论) - 工作演示
$(document).ready(function () {
var sum = 0;
var qty = 0;
$("input[type=checkbox]").change(function () {
if ($('#1').is(':checked')) {
$('#checked-1').show();
} else {
$('#checked-1').hide();
}
});
$('.qty').keyup(function () { // if user typed anyting in the Quantity
sum = parseInt($('#1').val()); // get checkbox value and change the data type to int
qty = parseInt($(this).val()); // get Quantity value and change the data type to int
//console.log(sum,qty);
if(sum && qty) { // if the values was not empty
$('#total').val(sum * qty); // show the result in the total element
} else { // if the values was empty
$('#total').val(''); // clear the result textbox
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.