I am trying to activate keyup
event on an input element, the problem is it didn't trigger once I press a key, I have to do another key event to activate it, which is not normal!
Here's my code:
$(".conv").keyup(function(){
var itemId = new Array();
$(".itemId").each(function() {
itemId.push($(this).text());
});
if (itemId.length == 0 || isEmpty($(this).val())) {
$(this).val('0.00');
return false;
}
if (!$.isNumeric($(this).val())) {
alert("Only numeric values are allowed in '" + $(this).parent().parent().find('th').text() + "' field.");
return false;
}
calcShipping();
});
I tried to use on
like this, but also not working:
$('body').on("keyup", ".plus", function(){
var itemId = new Array();
$(".itemId").each(function() {
itemId.push($(this).text());
});
if (itemId.length == 0) {
$(this).val('0.00');
return false;
}
calcShipping();
});
Calculate shipping function:
var calcShipping = function() {
if (isEmpty($(".totalCost2").text())) {
$(".totalCost2").text(parseInt($(".totalCost").text()));
}
var plus = 0;
var conv = parseInt($(".conv").val());
var tCost = parseInt($(".totalCost2").text());
var tQty = 0;
var tFinal = 0;
var tLast = 0;
var qty = 0;
var totalCost = 0;
var cost = new Array();
var qtyCost = new Array();
$("#txtItems2").attr('disabled','disabled');
$("#btnReset2").attr('disabled','disabled');
$("#uploadItems").attr('disabled','disabled');
$("#startUpload").attr('disabled','disabled');
$(".plus").each(function(){
if (isEmpty($(this).val())) {
$(this).val('0.00');
}
if (!$.isNumeric($(this).val())) {
alert("Only numeric values are allowed in '" + $(this).parent().parent().find('th').text() + "' field.");
return false;
}
plus += parseInt($(this).val());
});
$(".qty").each(function() {
qtyCost.push(parseInt($(this).text()));
tQty += parseInt($(this).text());
});
$(".cost").each(function() {
cost.push($(this).text());
});
tFinal = plus + tCost;
tLast = tFinal/tQty;
var qty = 0;
$(".cost").each(function(){
qty = parseInt($(this).parent().parent().find($(".qty")).text());
$(this).text(tLast * qty * conv);
qty = 0;
});
for (var i = 0; i < cost.length; i++)
{
totalCost += (cost[i] * qtyCost[i]);
}
$(".totalCost").text(totalCost.toFixed(2));
}
Any advice?
I found the problem, I have to recalculate the ".cost" after modifying it, not before, like this:
$(".cost").each(function(){
qty = parseInt($(this).parent().parent().find($(".qty")).text());
var newCost = tLast * qty * conv;
$(this).text(newCost);
qty = 0;
});
$(".cost").each(function() {
cost.push($(this).text());
});