(beginner) HTML + JS change variables with input value - javascript

Hello Stackoverflow people,
My question is how to change a variable I assigned with JavaScript using the value of an HTML input tag.
my progress:
<script type="text/javascript">
var x = 0;
document.write(x);
function addtox() {
var addx = document.getElementById("plusx").value;
x = x + addx;
}
</script>
<input id="plusx" type="number">
<input type="button" onclick="addtox()" value="add">
The result is that it literally adds the value of id="plusx" to the 0 that's already there. So if the input would be 50, it would return 050, and not 50. If I repeat the button it returns 05050 in stead of 100.
How can I fix this?
Also: how can I update text that is already writting to the screen? x is already written to the screenbefore the change and doesn't update after it is assigned a new value.
p.s
Sorry if I am a bit vague, not too familiar with coding questions like mine.

The value of an input element is a string type. You need to convert it to an integer:
x += parseInt(document.getElementById("plusx"), 10);

The return value from dom lookup is string. And so the result you are getting is string concatenation. Convert the return from dom lookup to integer using the parseInt () function. Then you should get the correct answer.

You can just put
X = "0" + addx;
This way you will always have the 0
- this will work if you just want to place a 0 In front.
if you want a more simple way of converting to integer just times your value by 1 will convert the strings to numbers.
So add in x = 0 * 1
And x= x + addx * 1
This will just give you your result without a 0 in front.
If you want 0 in front and number do
X = "0" + addx * 1;

Related

Adding multiple HTML form input values in JavaScript

I am bewildered as to why I cannot add three numbers together. Here is my HTML:
<div><label>Sales Price: </label>
<input type="number" name="sales_price" value="3">
</div>
<div><label>Incentives: </label>
<input type="number" name="incentives" value="2">
</div>
<div><label>Acquisition Fee: </label>
<input type="number" name="acq_fee" value="1">
Here is my JavaScript:
var salesPrice = document.getElementsByName("sales_price")[0];
var incentives = document.getElementsByName("incentives")[0];
var acqFee = document.getElementsByName("acq_fee")[0];
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
I wanted a simple calculation to be done: (3-2+1) = 2. However, netCapCost returns 11, which is the concatenation of the result of (3-2) and 1. What did I do wrong? Many Thanks in advance!
You need to convert those values into numbers with parseInt() or else the + operator will be interpreted as string concatenation. You are doing
var netCapCost = salesPrice.value - incentives.value + acqFee.value;
Which is
var netCapCost = "3" - "2" + "1"
"3"-"2" will return 1, which is what you want but 1 + "1" will be concatenated into "11" since the right operand is a string. So Number + String -> concatenation
var salesPrice;
var incentives;
var acqFee;
var npc;
function calculate(e) {
var netCapCost = (parseFloat(salesPrice.value) - parseFloat(incentives.value) + parseFloat(acqFee.value)).toPrecision(3);
npc.value = netCapCost;
}
window.onload = function (){
salesPrice = document.getElementsByName("sales_price")[0];
incentives = document.getElementsByName("incentives")[0];
acqFee = document.getElementsByName("acq_fee")[0];
npc = document.getElementsByName("npc")[0];
salesPrice.onchange = calculate;
calculate();
};
Your problem is that text fields value is always of type STRING. When subtracting it forces a conversion to type FLOAT. Then the plus operation shares an opperator with the concatenate operation. So when you have two strings being added it concatenates rather than converting to FLOAT or INT. So basically you have "2"-"1" being converted to 2-1 as strings cannot be subtracted which gives you (1) then you have (1)+"1" which will concatenate rather than add as you have a string. Always use parseFloat or parseInt when expecting numeric data from user entry as it will always be a string when originally submitted.
you are doing a string concatation, all value get from input value are string,
the first calcuation salesPrice.value - incentives.value is currect is becuase, the - sign convert the incentives.value to number
the currect way is
var netCapCost = parseInt(salesPrice.value, 10) - parseInt(incentives.value, 10) + parseInt(acqFee.value, 10);
it's better to use a Math library to do the calcuation in javascript, because sooner or later, you will encounter the problem like 0.3 - 0.2 = 0.09999999
I think confusion here is HTML 5 introduces input type number however javascript engine doesn't introduce support for reading such specific fields. We end up using old traditional way of reading input field value which defaults everything to string.
Only advantage of using number type field would be that you do not have to worry about exception/erroneous situation where number is not being entered.
Other answer suggesting to use parseInt function, is the way to go unless you have luxury of introducing javascript framework like jQuery and use more sophisticated approach for reading it.

Javascript to randomly add/subtract to a number every second

What I want my function to achieve for my javascript function is for every second to either randomly subtract or add (a random number) to a number held in a div.
Here's what I have so far.
It doesn't work, it seems to append the number to the end of the div value (100), and also it doesn't take into account that I want it to either randomly add or subtract (it just adds at the moment)
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);
parse the current value as an integer, and then do another math.random and use it to decide negative or positive. Lastly, you need to use the innerHTML of currentnumber, not the entire node. So something like this should work:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
WORKING FIDDLE
.innerHTML returns you a string which you'll need to parse into an integer to perform the addition or subtraction. Have a look at a number of methods listed in the following SO question
How do I convert a string into an integer in JavaScript?
currentnumber is a DOM object, and you can't add that to a number.
var div = document.getElementById('number');
div.innerHTML = Number(div.innerHTML) + 3;
Notice you are getting the innerHTML of the div, converting that to a Number(), adding your random number to it, and THEN setting your div.innerHTML to your new value.
http://jsfiddle.net/9LqQG/1/
Maybe try something like this:
setInterval(function(){
random = (Math.floor((Math.random()*15)+1));
currentnumber = parseInt(document.getElementById('number').innerHTML);
document.getElementById('number').innerHTML = currentnumber + random;
}, 1000);
Your currentnumber variable needs to get the innerHTML of the element, then parse the string into an integer.
jsFiddle

Simple math in jquery

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;

Addition operation issues?

Hi i'm trying to do simple addition of two numbers in javascript. When i'm trying to get the two input element values, the result is coming in a concatenation of two numbers
Here is the code:
<html>
<title>
</title>
<head>
<script type="text/javascript">
function loggedUser() {
//Get GUID of logged user
//alert('success');
var x, y , result;
x = document.getElementById('value1').value;
y = document.getElementById('value2').value;
result=x+y;
alert(result);
document.getElementById('res').value = result;
}
</script>
</head>
<body>
<input type="text" id="value1"><br>
<input type="text" id="value2"><br>
<input type="text" id="res">
<input type="submit" value ="submit" onclick=loggedUser();>
</body>
</html>
The "+" operator is overloaded. If any of the parameters is a string, they are all converted to strings and concatenated. If the parameters are numbers, then addition is done. Form control values are always strings.
Convert the parameters to numbers first using one of the following:
x = Number(document.getElementById('value1').value);
or
x = parseInt(document.getElementById('value1').value, 10);
or
x = parsefloat(document.getElementById('value1').value);
or
x = +document.getElementById('value1').value;
or
x = document.getElementById('value1').value * 1;
and so on...
Oh, you can also convert it only when necessary:
result = Number(x) + Number(y);
etc.
The input fields contain strings. If you want to sum two numbers, you have to convert the strings to numbers before adding - otherwise you are just adding two strings. There are lots of ways to do that depending upon what you want to allow. Here's one:
var x, y , result;
x = Number(document.getElementById('value1').value);
y = Number(document.getElementById('value2').value);
result=x+y;
alert(result);
document.getElementById('res').value = result;
See it working here: http://jsfiddle.net/jfriend00/BWW2R/
document.getElementById('').value returns a string. You need to call parseInt on that to make it a number.
It's because x and y are actually strings, not numbers. The value field of the element is always a string, so x+y gives you the concatenation of x and y.
You can parse x and y as integers and add the result of the parsing: that will give you what you want.
The problem is when you take those values you are getting a string and in result you are doing a concatenation. You should use parseInt on both x and y like this:
x = parseInt(document.getElementById('value1').value);
y = parseInt(document.getElementById('value2').value);

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories