Salman Razak
Salman Razak

Reputation: 85

Javascript random numbers for different <li>

I have many <li> with different height and width. I want to generate random numbers for every list style. For example 10 list styles have different innerHTML numbers inside. Please correct me if I am wrong.

function getNumber() {
    var minNumber = 0;
    var maxNumber = 10;
    var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
    for (i = 0; i < 5; i++) {
        $('ul li').html(randomnumber);
    }
    return false;
}

Please guide me or give me advice. Thanks.

Upvotes: 0

Views: 748

Answers (2)

tmnd91
tmnd91

Reputation: 449

That's the right way to do it. Running the code when the DOM is fully loaded with $() and maybe putting the logic of random number generation in a different function for better reusability. You can copy-paste the code above to a text file to test it.

<html>
    <head>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script>
            function getRandomNumber(minNumber, maxNumber){
                return Math.floor(Math.random() * (maxNumber + 1) + minNumber);
            }
            $(function(){
                var minNumber = 0;
                var maxNumber = 10;
                $("ul li").each(function(){
                    $(this).html(getRandomNumber(minNumber,maxNumber));
                });
            });
        </script>
    </head>
    <body>
        <ul>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </body>
</html>

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337570

The main issue with your code is that you assign the same random number to all the li elements in each iteration of the loop. Instead you should loop over each li element and generate a new random number in each iteration. Try this:

function getNumber() {
    $('ul li').each(function() {
        var minNumber = 0;
        var maxNumber = 10;
        var randomnumber = Math.floor(Math.random() * (maxNumber + 1) + minNumber);
        $(this).html(randomnumber);
    });
}

Example fiddle

Upvotes: 2

Related Questions