i have a Invoice form and a jquery function.
In Invoice if i enter the quantity greater then the available quantity then i have to alert the user.
My problem is: Let the max quantity is 5, if i input data as 7 (single digit>max avail quantity) then my code is working fine. But if i enter two digigist number eg. 17(two digists>max avail quantity) then my alert box is not coming.
I mean onkeyup my function is working only with single digit.
How can i make it happening? Please help.
$('input[name="quantity"]').keyup(function()
{
//problem is here
var $tr = $(this).closest("tr");
var unitprice = $tr.find('input[name^="unitprice"]').val();
var q = $tr.find('input[name^="quantity"]').val();
var cq = $tr.find('input[name^="checkquantity"]').val();
if(q>cq)
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is "+cq);
//this works fine only if single digit is entered in textbox quantity
}
//----below are some other stuffs -these are working fine
$tr.find('input[name^="sprice"]').val($(this).val() * unitprice);
var totalPrice = 0;
$('input[name="sprice"]').each(function()
{
totalPrice += parseFloat(this.value);
$('[name=subtotal]').val(totalPrice);
});
});
--------------
------------
// Form containing the above textboxes
<input type="submit" id="submitbtnId" value="Save"/>`
q > cq is comparing 2 strings, which is not what you want. You're trying to compare the numerical value of those strings.
Use this instead:
if ( +q > +cq)
{
// alert your error
}
Note that by prefixing the variables with the + sign, you're converting them to a number.
Better yet, convert them to a number as soon as you get the values:
var $tr = $(this).closest("tr");
var unitprice = +$tr.find('input[name^="unitprice"]').val();
var q = +$tr.find('input[name^="quantity"]').val();
var cq = +$tr.find('input[name^="checkquantity"]').val();
if ( q > cq )
{
alert("Error: Quantity value exceeds then available quantity..Max Quantity is " + cq);
}
You need to use parseInt() to ensure you are comparing integers, not strings:
if (parseInt(q, 10) > parseInt(cq, 10)) {
/* Rest of your code */
}
Your values are compared as string. If you want to compare Numbers, either use:
parseInt() or parseFloat()
or
[..].val() * 1, but this will return 'NaN' if its no digit, while parseInt() and parseFloat() will return 0
Related
Trying to build a Javascript %age Discount calculator for my webshop. The problem is that the calculator calculates some products wrong by 2-10%. Please help, whats wrong in the code?
<script type="text/javascript">
$(document).ready(function() {
/*
Least allowed discount to show.
*/
var minDiscount = 15;
$('.gridArticlePrices').each(function() {
/* Get ordinary price */
var oldPrice = $(this).children('.gridArticlePriceRegular').html();
/* Get sale price */
var newPrice = $(this).children('.gridArticlePrice').children('.reducedPrice').html();
if ((oldPrice) && (newPrice)) {
/* Convert to numbers instead of strings */
var oldPrice = parseInt(oldPrice.replace("/[^0-9]/g", ""));
var newPrice = parseInt(newPrice.replace("/[^0-9]/g", ""));
/* Calcuate the precentage, rounded of to 0 decimals */
var discount = Math.round(100 - ((newPrice / oldPrice) * 100));
/* If the precentage is higher than "var min Discount" then write out the discount next to the products price.*/
if (discount >= minDiscount) {
$(this).parent().after("<div class='discount'>-" + discount + "%</div>");
}
}
});
});
</script>
UPDATE:
My original suggestion to use parseFloat was assuming your prices included decimal components. As I see now, they are in fact integers, so parseInt works fine.
The actual issue is your replace() call isn't removing anything. You should remove the quotes around the regex, and then it will remove the extra characters you don't want.
var oldPrice = parseInt(oldPrice.replace(/[^0-9]/g, ""));
var newPrice = parseInt(newPrice.replace(/[^0-9]/g, ""));
Note: If you do need to handle decimal prices, you would need to add "." to you regex (so it doesn't get removed), and use parseFloat instead of parseInt.
var price = "$23.03";
var newPrice = price.replace('$', '')
This works, but price can also be such as:
var price = "23.03 euros";
and many many other currencies.
Is there anyway that I could leave only numbers and decimal(.)?
var newPrice = price.replace(/[^0-9\.]/g, '');
No jQuery needed. You will also need to check if there is only one decimal point though, like this:
var decimalPoints = newPrice.match(/\./g);
// Annoyingly you have to check for null before trying to
// count the number of matches.
if (decimalPoints && decimalPoints.length > 1) {
// do whatever you do when input is invalid.
}
var newprice = price.replace( /\D+$/, '');
Im using the following method to add up text boxes. I have tried changing multiple things and cant seem to multiply two text box values! essential I want 2 text box that values are multiplied and displayed in a third text box. I want this value to be fluid aka change when the number changes! I was using this code because i may be multiplying more then one thing but if this is too much of a hassle i will live with just multiplying two at a time
The code im using to add is
<!--adding script #-->
<script>
$(document).ready(function(){
calculateSum();
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
var total = document.getElementById("subtotal").value == "";
var total = document.getElementById("subtotal").value = sum;
}
<!--END adding script #-->
I tried setting the last line to
var times1 = document.getElementById(subtotal);
var times2 = document.getElementById(tax);
var equal = times1.value * times2.value;
and then changing var total1 = document.getElementById("total1").value = sum9; to var total1 = document.getElementById("total1").value = equal;
The text boxes id are subtotal and tax the box im trying to update is total1.
Thanks alot!
On every keyup, instead of getting all values and adding them explicitly, it is better to deduct the previous value of the corresponding input and add the current updated value to sum..
Also, if subtotal is correctly calculated, then the multipication operation what ever you have done should work correctly..
Please find the following jsfiddle where the sum is calculated as explained above along with multiplying the tax..
http://jsfiddle.net/tgvrs_santhosh/77uxK/1/
Let me know if you still face the issue..
Instead of this
if(!isNaN(this.value) && this.value.length!=0) {
I think a regular expression may work better because you are using string values
if (/^([-]?((\d+)|(\d+\.\d+)|(\.\d+)))$/.test(this.value)) {
I haven't tested this regex, but you should be able to find a good regex to test for valid numbers if this one doesn't work for some reason. Also I noticed you have a == after that getElementById.
I'm not totally certain it matters, but you can do sum += (this.value * 1) instead of parseFloat.
update
Try this var equal = ($("#subtotal").val() * 1) * ($("#tax").val() * 1);
I found your question very confusing, but I think what you're trying to say is you want to add up all the .txt fields to get a sub-total, then multiply that sub-total by a tax rate to get a total. If so, then you already know the sub-total is a valid number due to the way you calculate it, so then:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
If your tax field is not an input then use .text() instead of .val().
Your existing code is rather more complicated than it needs to be. You can do this:
$(document).ready(function(){
calculateSum();
// you don't need an .each() loop, you can bind a keyup handler
// to all elements in the jQuery object in one step, and you don't
// need the anonymous function since it does nothing but call calculateSum:
$(".txt").keyup(calculateSum);
});
function calculateSum() {
var sum = 0,
val;
//iterate through each textboxes and add the values
$(".txt").each(function() {
// you don't need to test for NaN: just attempt to convert this.value
// to a number with the unary plus operator and if the result is not
// a number the expression val = +this.value will be falsy
if(val = +this.value)
sum += val;
});
$("#sum").html(sum.toFixed(2));
var tax = +$("#tax").val();
$("#total1").html((tax ? sum * tax : sum).toFixed(2));
}
For some reason the unary plus operator used throughout my answer is not widely known, but I prefer it to parseFloat().
as you can see in the picture, it would be silly for the user to have to type in all 5 Requested Brands (as that is not required). Maybe they only want to choose one Requested Brand. As it is currently set up, the subtotal is only calculated if the user enters 5 unit costs and 5 quantities...not good. If they don't enter all 5, subtotal returns NaN.
$("a#full_sub_total").click(function(event){
event.preventDefault();
var first = $("div#total_result").text();
var second = $("div#total_result1").text();
var third = $("div#total_result2").text();
var fourth = $("div#total_result3").text();
var fifth = $("div#total_result4").text();
$("#full_total_results p").text((parseInt(first,10) + parseInt(second,10) + parseInt(third,10) + parseInt(fourth,10) + parseInt(fifth,10)));
});
Any help is greatly appreciated.
I would loop over the total_result fields, and incrementally add their parsed values to a total var:
$("a#full_sub_total").on("click", function(){
var total = 0;
$("div[id^=total_result]").text(function(i,t){
total += parseInt( t, 10 ) || 0;
});
$(".full_total").text("$" + total);
});
Note the main part of all of this:
total += parseInt( t, 10 ) || 0;
When the attempt to parse an integer from the text of the element fails, we return 0 in its place. This will not offset the total value, and will permit us to continue along with out any NaN showing up later.
Demo: http://jsbin.com/axowew/2/edit
Basic technique:
var sum = 0;
var num1 = parseInt(text1, 10);
if (!isNaN(num1)) sum += num1;
// ...
(Loops: even better idea.)
The problem your overall total results in NaN is that anytime one or more of individual line total is empty, it will cause your overall result total to equal NaN in your attempt to add (i.e. #+#=#, #+NaN=Nan)
Simplify solution to your problem:
$('#subtotal').click(function(e) {
e.preventDefault();
// Clear overall total
$('#overallTotal').empty();
// Loop through each line total
$('div.lineTotal').each(function() {
// If line total is not empty, add
if ($(this).text() != ''){
$('#overallTotal').text(parseInt($('#overallTotal').text) += parseInt($(this).text()));
}
});
});
I'm attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN as the total. I believe it may be the way I'm declaring the subtotal variable in my script, but I haven't come across this before:
$('.item-qty input').bind('keyup', function(){
var subtotal = 0.0;
$('.item-qty input').each(function(){
var class = $(this).attr('id');
var qty = $(this).val();
var price = $('.'+class).html();
price = parseFloat(price);
qty = parseInt(qty);
subtotal = subtotal + (price * qty);
});
$('.subtotal input').val(subtotal);
});
parseFloat and parseInt can return NaN if the first character of the string cannot be converted to a number.
So, I would safeguard against it like this (NaN is a falsy value):
price = parseFloat(price) || 0;
qty = parseInt(qty, 10) || 0;
Arithmetic operations on numbers with the value NaN almost always result in NaN (NaN + 5 will result in NaN.) That means, if only one of the input cannot be parsed by parseFloat or parseInt, your current code would end up calculating NaN for the subtotal.
It's already been mentioned in the comments (by Felix mostly) but I think it's worth the emphasis as these are important concerns:
Always pass the radix argument to the parseInt function;
Do not use class for variable names: It's a reserved (not used, but reserved) keyword;
Don't expect the subtotal to be perfectly accurate unless you do your calculations in cents.