HanSolo0001
HanSolo0001

Reputation: 9

Why is this Javascript code not adding to input?

I'm taking user input and using Javascript to add 5 to the number provided. Javascript puts number together (1 becomes 15 and not 6). It also is opening it in a new page; I want it in its own paragraph beneath it. Am I over complicating this?

I created a function to call to take user input, check if number is between 0 and 10, and if yes add 5 to it. If it is not, then an error message would appear to say input a number between 0 and 10. Code is down below, and here is the GitHub repo I made for it as well.

// This code checks if input is between 0 and 10. If it is code will run (in this case addition), if not error message occurs. 
function number() {
    var myNumber = document.getElementById('inputNumber').value;
    if (myNumber >= 0 || myNumber <= 10) {
        var result = myNumber + 5;
        document.write(result).innerHTML;
    } else {
        document.write("Please input a number between 0 and 10.");
    }
}
<section>
        <span>Enter a number between 0 and 10.</span><br>
        <textarea id="inputNumber" label="Enter a number between 0 and 10."></textarea>
        <br>
        <button id="numberResult" onclick="number()">Click here to run addition Javascript!</button>
        <p id="myResult"></p>
    </section>

So the Javascript is supposed to take the user input (number between 0 and 10) and add it to 5. What's happening is the number is just tagged onto the 5 and opened up in a new page when button is clicked to show result. i.e. 1 becomes 15 and not 6 (1 + 5).

Upvotes: 0

Views: 72

Answers (1)

Amol Bhandari SJ
Amol Bhandari SJ

Reputation: 278

You will need to convert string to integer first

var result = Number(myNumber) + 5;

then assign value to the p tag with id myresult

document.getElementById("myResult").innerHTML = result;

Upvotes: 4

Related Questions