Damir Gasparlin Damir Gasparlin - 2 months ago 11
HTML Question

different random number in each div

This is probably simple but I can't get it to work.

I have working code that inputs random number inside div but it inputs same random number in all divs on the page.

How can I input different random number in each div?
Here is my code:

<script>
var randomNumber = Math.random();
var num = Math.floor((randomNumber * 75) + 15);

jQuery('#sale').each(function() {
jQuery(this).find('.savings').append(num);
});
</script>


Yes I'm looping on # since class is inside, should I loop on class itself?
Here is the html:

<div class="col-md-6 itemcol">
<div class="">
<div id="sale" class="sale" style=""><span class="savings"></span>% OFF<br></div>



Answer

Try this :

$(document).ready(function() {

    $("#sale .savings").each(function(){
        $(this).text(createRandom());
    })

    function createRandom() {
        var Num = Math.floor((Math.random()*75) + 15);
        return Num;
    }       
})

Final code :

<!DOCTYPE html>
<html>
    <head>
        <style>
            .savings {
                border: 2px solid red;
                width: 200px;
                height: 50px;
                margin-bottom: 1px;
            }
        </style>
    </head>
    <body>
        <div id="sale">
            <div class="savings"></div>
            <div class="savings"></div>
            <div class="savings"></div>
            <div class="savings"></div>
        </div>
        
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
$(document).ready(function() {
    
    $("#sale .savings").each(function(){
        $(this).text(createRandom());
    })
    
    function createRandom() {
        var Num = Math.floor((Math.random()*75) + 15);
        return Num;
    }       
})          
        </script>
    </body>  
</html>