length does not work after multiplication - javascript

Edit: Solution: http://jsfiddle.net/VnXtP/
Why dosent this work?
http://jsfiddle.net/uc7kT/
<input type="text" name="item_quantity" id="item_quantity" value="1" />
<input type="text" name="item_price" id="item_price" value="24998" hidden="hidden" />
$('#item_quantity').change(function() {
var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
var total = quantity * price;
alert(total.length);
});

Length is defined for strings, not numbers. If you wish to do this as a mathematical operation, you must convert the input strings to numbers first. If you actually want the length of the number string (I don't know why you would), you need to convert the number to a string first:
$('#item_quantity').change(function() {
var quantity = parseInt($('#item_quantity').val(), 10);
var price = parseFloat($('#item_price').val());
var total = quantity * price;
alert(total.toString().length);
});

Use:
alert(total);
Instead of:
alert(total.length);
You may also want to consider converting the values of the input to a float, or integer value before performing the math.
http://jsfiddle.net/samliew/uc7kT/5/

total is a number. It does not have the property "length".
Try
alert(total);
I guess that is what you want.

In javascript a number is a number and a string is a string.
What can be sometimes confusing is that a number can automagically become a string when that is needed (for example adding a string to it).
Numbers do not have a length property, strings instead do. Also in javascript when you ask an object for a property that is not present normally you just get the undefined value.

var quantity = $('#item_quantity').val();
var price = $('#item_price').val();
item_quantity and item_price are text inputs, and you need to change it to Integer before you multiply. use parseInt() to do it.
var quantity = parseInt($('#item_quantity').val(),10);
var price = parseInt($('#item_price').val(),10);
and use alert(total); not alert(total.length);

Related

How to calculate with numbers in jquery?

I am wanting to subtract some values of inputs with the total price.
The code:
$('.calculate-resterend').click(function(e) {
e.preventDefault();
var contant = $('.checkout-contant').val();
var pin = $('.checkout-pin').val();
var creditcard = $('.checkout-creditcard').val();
var waardebon = $('.checkout-waardebon').val();
var totalprice = $('.total.final-price.price').text();
alert(contant - totalprice);
});
But this returns NaN. I figure it's because total price is .text();,
but what is the correct way to substract between these things.
Lets say var contant has a value of 2000,98
and the total price has a value of 2400,99
I want it to return 400,01.
Use Number()
alert(Number(contant) - Number(totalprice));
If you also want to remove comman(,)
alert(Number(contant.replace(/\,/g,'')) - Number(totalprice.replace(/\,/g,'')));
You may have to convert one of your values using parseInt. You can try the following:
totalprice = parseInt(totalprice)
And then proceed to do your simple subtraction like before. You could also try to make your own price attribute on the HTML element itself and the fetch the attribute value instead like .attr("price"). Not sure if that would return a string as well.
try to convert your value by using parseint()
eg:- parseint(your_value)

javascript concat() , want to concat 5 different value of string

I have text box with 5 digit numbers given by user,for ex:-if num2=(12345), I want to individual number to be subtract by 10. So the answer for 12345 will be 98765. I have used charAt() to separate the numbers and store in different variables. Then used concat() Which is not working. I am wondering their must be some different efficient approach to get required answer.
<input id="num2" type="text" /><br />
<input id ="comRanNum" type="text" /><br />
<input name="" type="button" onclick="check()" value="Click Here" />
function check()
{
var num2=document.getElementById("num2").value;
var temp0=10-num2.charAt(0);
var temp1=10-num2.charAt(1);
var temp2=10-num2.charAt(2);
var temp3=10-num2.charAt(3);
var temp4=10-num2.charAt(4);
var temp5=temp0.concat(temp1,temp2,temp3,temp4);
document.getElementById("comRanNum").value=temp5;
}
If your problem always involves 5 numbers, you could simply use 111110-num2. E.g., 111110-12345=98765. To solve the issue for a dynamic amount of numbers, you could make the number of 1s depend on how long the entered number is.
temp0 isn’t a string yet, so you can’t call concat on it. But if you’re converting it to a string anyways, why bother?
var temp5 = '' + temp0 + temp1 + temp2 + temp3 + temp4;
Since you specify exactly five digits, though, TVK’s answer is best. Math is always best.
var num = '12345';
var result = num.split('').map(function (item) {
return 10 - item;
}).join('');
console.log(result); // 98765

Javascript add to value if smaller than another value error for more than one digit

I've got a javascript function that adds one to a quantity if the current value is less than another value. Here is the javascript function:
function addQty()
{
if(document.getElementById("quantity").value < document.getElementById("stock").value)
document.getElementById("quantity").value++;
else
return;
}
And here are the form elements that the values are taken from:
<input type='text' id="quantity" name='quantity' value ='0' />
<input type='hidden' id="stock" name="stock" value="<?php echo $adjustedStock; ?>" />
So basically the user can add one to their quantity of a product to order only if there is enough in stock.
Now, this works absolutely fine if the number in stock is 1-9, but if the stock level is in double digits, the maximum the user can add to their basket (ie the 'quantity' in the code) returns as the first digit + 1. So if the stock is 13 then the max quantity is 2, or if the stock is 63 the max quantity is 7.
I've tried converting the integer value of $adjustedStock to a string before it is used in the form as I read sometimes browsers can behave weirdly in this situation, but this didn't work. Any ideas why this is happening?
Thanks in advance!
The "value" attribute of an <input> is always a string. Thus your comparison is being done between two strings, which is not what you want.
Convert the values to numbers before comparing:
function addQty()
{
var qtyInp = document.getElementById('quantity'),
qty = parseInt(qtyInp.value, 10),
stk = parseInt(document.getElementById('stock').value, 10);
if (qty < stk)
qtyInp.value = qty + 1;
}
Form element values are strings. Use parseInt or convert to a number some other way.
You can use Math.min() for this purpose...
function addQty() {
var quantity = document.getElementById("quantity");
quantity.value = Math.min(+quantity.value + 1,
document.getElementById("stock").value);
}
This makes it very clear that you want the lesser of the incremented quantity or the total in stock.

jQuery/Javascript splitting string calculation

I'm creating a product page that requires the price to update when the quantity value is changed. Two form fields are used: .orig_price and #quantity. These values are obviously multiplied together.
I'm trying to split the multiplied value, so that I can print the correct format (27.7043454575 should be 27.70).
My code:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = jQuery(".orig_price").val().substr(1);
var qty = jQuery("#quantity").val();
// calculate price
var sumValue = origprice * qty;
// split price
var splitprice = sumValue.split(".");
var pricepound = splitprice[0];
var pricepenny = splitprice[1].substring(0,2);
// update price
jQuery("#pricediv").html('£' + pricepound + '.' + pricepenny);
jQuery("#pricediv").fadeIn(1500);
});
If I remove the split and use sumValue everything works (but format is wrong). Does split not work on a calculation?
You'll want to use sumValue.toFixed(2)
var sumValue = 27.7043454575;
sumValue.toFixed(2) // 27.70
.split does not exist on numeric types. You would have to use sumValue.toString().split('.'), and either way, this would be more inconvenient than simply sticking to .toFixed
You can use toFixed and parseInt() like so:
jQuery("#quantity").change(function() {
jQuery("#pricediv").hide();
// store form values
var origprice = parseInt(jQuery(".orig_price").val().substr(1),10);
var qty = parseInt(jQuery("#quantity").val(),10);
// calculate price
var sumValue = origprice * qty;
// split price
var price = sumValue.toFixed(2);
// update price
jQuery("#pricediv").html('£' + price);
jQuery("#pricediv").fadeIn(1500);
});
toFixed determines the number of points after a decimal, and parseInt type-casts the input to an integer (the 10 is unnecessary but there to show it's decimal base 10), because when getting data from a form field it sometimes comes back as a string and messes up your math.

simple calculation of integer and decimal number in jquery

Trying to multiply 2 values. Quantity is integer and credit price is decimal number. When I run this code nothing happens.
Does anyone know what is the issue?
Thank you.
$(function(){ // bind the recalc function to the quantity fields
$("#oneCreditSum").after('<label></label>Total: Aud <span id=\"total\"></span><br><br>');
$("#quantity").bind('keyup', recalc);
function recalc(){
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = quantity * creditPrice;
$("#total").text(total);
}});
Use parseFloat on the values, and alert each one individually to test.
A few other (unrelated) improvements:
Use keyup() function:
$("#quantity").keyup(recalc);
Make function anonymous:
$("#quantity").keyup(function(){...});
Use $(this) on #quantity in the function to avoid calling the jQuery selector again
You could also consider condensing this into a single line of code:
$("#total").text(parseFloat($('#quantity').val()) * parseFloat($('#creditPrice').val()));
To zero-pad you might try something toFixed():
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
I got this snippet from the following site
http://www.mredkj.com/javascript/numberFormat.html
Hope this helps.
use
parseFloat
before calculation on both numbers which parses a string argument and returns a floating point number.
var quantity = $('#quantity').val();
var creditPrice = $('#creditPrice').val();
var total = parseFloat(quantity) * parseFloat(creditPrice);
If you are interested in whole number only you can use this function instead:
parseInt

Categories

Resources