Thijs
Thijs

Reputation: 91

(beginner) HTML + JS change variables with input value

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.

Upvotes: 0

Views: 101

Answers (3)

Creaven
Creaven

Reputation: 319

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;

Upvotes: 0

Schism
Schism

Reputation: 275

The value of an input element is a string type. You need to convert it to an integer:

x += parseInt(document.getElementById("plusx"), 10);

Upvotes: 2

Jerome Anthony
Jerome Anthony

Reputation: 8041

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.

Upvotes: 1

Related Questions