Trouble with adding numbers in Javascript? - javascript

I want to add the price of some books when each one checked but I have a problem.
It just adds a string. For example, when I select a book(10$), the price becomes 10 and when I select another book(20$) it becomes 1020, and so on...
My code :
For book one :
<input
name="bookList"
type="checkbox"
id="bookList_1"
onChange="
if (document.getElementById('bookList_1').checked) {
document.getElementById('priceDes').innerHTML=' total: ';
document.getElementById('price').innerHTML+=10;
}
"
value="book1"
>
For book two :
<input
name="bookList"
type="checkbox"
id="bookList_2"
onChange="
if (document.getElementById('bookList_2').checked) {
document.getElementById('priceDes').innerHTML=' total: ';
document.getElementById('price').innerHTML+=20;
}
"
value="book1"
>
And the price and priceDes are <p> tags ...
Thanks for your solutions ;)

It's because you're concatenating strings, instead of adding numbers. '10'+'20' gives '1020' and not 30.
Try:
document.getElementById('price').innerHTML=parseInt(document.getElementById('pr‌​ice').innerHTML)+10;
Be careful with this though, it would only work if your p tags have only the numbers inside their HTML. parseInt('10$') gives 10 but parseInt('$10') gives NaN. You can experiment with number-type input tags.

document.getElementById('price').innerHTML=Number(document.getElementById('price').innerHTML)+20;

InnerHTML is a string. The + operator is also the String concatenate operator in JavaScript. So, "cast" the values first.
Easy way to "cast" numerical strings in JavaScript: multiply by 1:
var rv = 1*a.innerHTML + 1*b.innerHTML;
Or, use the Number constructor:
var rv = Number(a.innerHTML) + Number(b.innerHTML);

Related

Formatting Price Input

ideally this is for AS3, but I can always convert it down from JavaScript. Basically I want type numbers into a field and have it add the decimal. The issue is, the keyboard won't have a "." key
So if the final output was 10.45
it would automatically start to format as I type:
1 it would change to .01. And as I keep typing..
.01
.10
10.40
10.45
This can be accomplished by some simple string manipulation. Just split the string into parts and insert the decimal.
HTML
<input type="text" id="price" onchange="formatPrice(this)" />
Javascript
function formatPrice(obj) {
//remove any existing decimal
p = obj.value.replace('.','');
//get everything except the last 2 digits
var l = p.substring(-2, p.length-2);
//get the last 2 digits
var r = p.substring(p.length-2,p.length);
//update the value
obj.value = l + '.' + r;
}
You can see it working here: https://jsfiddle.net/x3wey5uk/

Sorting words according to length in textarea using html & javascript

<div align="center">
<textarea style="overflow:auto;resize:none" id="sorter3" name="sorter3" rows="4" cols="50" maxlength="100" wrap="hard"></textarea><br>
<input type="button" value="words in Asc" onClick="SortWords()">
</div>
This is my html page for that corresponding javascript is:
function SortWords(){
var inputvalues=document.getElementById("sorter3").value.split("");
inputvalues.sort();
//alert(inputvalues)
alert(inputvalues[0])
document.getElementById("sorter3").value=inputvalues;
}
it is showing the output based on words initials but i need output based on length:
example: when i enter some thing in text area as : welcome to javascriptworld it is a independent langauage, expected output is : smallest word is 'a' and longest word is 'javascriptworld' can anybody help me how to do this
You just need to sort your inputvalues array(using split(' ') instead of split('')) based on the string-length of individual elements.
var inputvalues=document.getElementById("sorter3").value.split(" ");
inputvalues.sort(function(x, y) {return x.length>y.length;});
DEMO
I think you just need to change your
split("");
to
split(" ");
That way it will divide the string using the spaces rather than splitting it into each individual character.
As for the sort, if you send it a function as a parameter, it'll sort using the function as the comparison type. Maybe something like this (untested):
.sort(function (a, b) { return a.length - b.length; } );
The rest should be fairly straight forward.

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

Parsing integers in AngularJS

I am using AngularJS in one of our application.
In the code below, while loading the page the expression addition (number, valuetoadd) parses correctly and give output as 1+1=2 but while changing the input it doesn't parse correctly and it gives output as `1+2=12'.
Where do I need to change?
<div ng-controller='MathsController'>
<input type="range" min="0" max="100" step="1" value="1" ng-model='valuetoadd'/>
<p>Addition table of <b>{{valuetoadd}}</b></p>
<div ng-repeat='number in numbers'>
{{number}} + {{valuetoadd}} = {{ addition(number,valuetoadd) }}
</div>
</div>
<script type="text/javascript">
function MathsController($scope)
{
$scope.valuetoadd= 1;
$scope.numbers =[1,2,3,4,5,6,7,8,9,10];
$scope.addition = function(number,valuetoadd)
{
return number+valuetoadd;
}
}
</script>
May be number beging passed as a string.
Try:
$scope.addition = function(number, multiplier)
{
return + number + multiplier;
}
+ would convert the string into number.
EDIT:
Now, I see that multiplier is passed as string.
So IT has to be converted instead...
Sorry that I did not read the code carefully.
$scope.addition = function(number, multiplier)
{
return number + +multiplier;
}
Thank you #Artur for pointing this out.
Seems like the root of the problem lies here:
https://github.com/angular/angular.js/issues/1189
Also read this SO topic: Two-way binding with range and number input in AngularJS
As a workaround you can use the solutions proposed by thefrontender and tosh shimayama.
It's worth noticing, though, that it is the multiplier who requires parsing to integer, not the number. See my comment to your question.
Another quick fix is to multiply value by 1 before addition. This will force JavaScript to convert value from string to integer.
Example:
{{value*1 + 10}}
You need to coerce the variables into some sort of numeric type (values from HTML inputs are passed as string by default)
$scope.addition = function (number, multiplier) {
return number + parseInt(multiplier, 10);
}

length does not work after multiplication

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);

Categories

Resources