Reputation: 51
var randNum = function(){
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
addTXT(num);
}
};
This function is supposed to take the numbers typed into the text boxes with the IDs 'min', 'max', and 'reps', and use them to come up with some random numbers. It doesn't write anything to the HTML document. The addTXT() function should write the number to a div, and I know it works because I've used it just fine before this. Any help would be appreciated. Also, I've been working with javascript less than a week, so I'm suspicious the problem is really obvious and I just don't see it.
var addTXT = function(newText){
var outputDiv=document.getElementById("console");
var oldText = outputDiv.innerHTML;
outputDiv.innerHTML = newText + oldText;
};
Upvotes: 1
Views: 132
Reputation: 1095
Where do you get the issue? If you unsure, try to put an alert in on certain spots in your code.
For example:
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
addTXT(num);
}
};
If your addTxt function does not work, try the jQuery way
var randNum = function(){
alert('Function is triggered');
var max = document.getElementById('max').value;
var min = document.getElementById('min').value;
var reps = document.getElementById('reps').value;
var i;
for (i=0; i<reps; i++){
var num = min + Math.floor(Math.random() * (max - min + 1)); //rand # 0-(max-1)
alert(num);
$('#console').append(num);
}
};
Upvotes: 0
Reputation: 91309
Parse the string values into integers with parseInt()
:
var max = parseInt(document.getElementById('max').value);
var min = parseInt(document.getElementById('min').value);
var reps = parseInt(document.getElementById('reps').value);
DEMO.
Upvotes: 1