1

Need help with Javascript to generate number in HTML. I'm close but can't get it to quite work. Help would be appreciated.

http://jsfiddle.net/xmPgR/251/

function getNumber() {
    var minNumber = 0; // The minimum number you want
    var maxNumber = 100; // The maximum number you want
    var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
    $('#myNumber').html(randomnumber); // Sets content of <div> to number
    return false; // Returns false just to tidy everything up
}

window.onload = getNumber; // Runs the function on click
document.getElementById("yourNumber").innerHTML = randomnumber;
<div id="myNumber"></div>
<p id="yourNumber">
</p>

0

2 Answers 2

3

Your onload works after the next statement, because it works asynchronously. And besides this, you use a randomnumber outside from it's scope, where it is not accessible.

So I suggest you to return the randomnumber from the function and use that function in the onload event handler. Inside that handler call your function, get the number and assign to your element's text.

And also if your getNumer's logic is to return the number, don't assign anything inside it, just return the number. It's responsibility is to return a random number. Pass the range to it, don't hard code: in another place you can need a random number in the different range. Other logic implement outside of that function.

function getRandomNumber(minRange, maxRange) {
    return Math.floor(Math.random() * (maxRange + 1) + minRange);
}

window.onload = function() {
    const rand = getRandomNumber(0, 100);
    document.getElementById("yourNumber").innerHTML = rand;
    $('#myNumber').html(rand);
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myNumber"></div>
<p id="yourNumber"></p>

Sign up to request clarification or add additional context in comments.

1 Comment

@Bylonb If this helps you, you accept it and help others to find it
2

Here you go:

function getNumber() {
    var minNumber = 0; // The minimum number you want
    var maxNumber = 100; // The maximum number you want
    var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber); // Generates random number
    document.getElementById("myNumber").innerHTML = randomnumber; // Sets content of <div> to number
    return false; // Returns false just to tidy everything up
}

window.onload = getNumber; // Runs the function on click
<div id="myNumber"></div>
<p id="yourNumber">
</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.