Reputation: 51
I'm trying to add 5 more numbers to the number that the user puts in but it only goes up to 5. For example if I put 2 it should add 5 more numbers to it so the output should look like this 2 3 4 5 6
function myFunction() {
var getDiv = document.getElementById("mydiv");
var input = document.getElementById("test").value;
if (!isNaN(input)) {
parseInt(input);
for (var i = input; i <= 5; i++) {
getDiv.innerHTML += i;
}
} else {
getDiv.innerHTML += input + " is not a number!!<br />";
}
}
Upvotes: 0
Views: 805
Reputation: 4467
Try this, which adds input = parseInt(input);
to make input
a number, and alters your loop to a range of 5.
function myFunction() {
var getDiv = document.getElementById("mydiv");
var input = document.getElementById("test").value;
if (!isNaN(input)) {
input = parseInt(input);
for (var i = input; i < input + 5; i++) {
getDiv.innerHTML += i + ' ';
}
} else {
getDiv.innerHTML += input + " is not a number!!<br />";
}
}
<div id="mydiv"></div>
<input id="test"></input>
<button onclick="myFunction();">Click me</button>
Upvotes: 3
Reputation: 2829
You can loop from 0 to 4 both included and add that each time to the input value, note that you should cast the string input
, so parseInt(input);
should be input = parseInt(input);
because if you don't update input
to a number then it will stay the same string and adding a number to astring just concatenate it so "30" + 5 = "305" and the loop will run for that number!
function myFunction() {
var getDiv = document.getElementById("mydiv");
var input = document.getElementById("test").value;
if (!isNaN(input)) {
input = parseInt(input);
for (var i = 0; i < 5; i++) {
getDiv.innerHTML += i + input;
}
} else {
getDiv.innerHTML += input + " is not a number!!<br />";
}
}
<div id="mydiv"></div>
<input id="test"></input>
<button onclick="myFunction();">Click me</button>
Upvotes: 1