So, say I have a number, c, and when I click a button it randomly increases by another number, b, which is any number between 1-10. I have tried math.floor(math.random()) and document-getElementById('#id').innerhtml="". Please help, preferably save c as a variable. Thanks.
            Asked
            
        
        
            Active
            
        
            Viewed 301 times
        
    -1
            
            
        - 
                    1Show us the code that you have. – Tyler Jan 07 '14 at 22:18
- 
                    possible duplicate of [Generate random value between two numbers in Javascript](http://stackoverflow.com/questions/4959975/generate-random-value-between-two-numbers-in-javascript) – Niet the Dark Absol Jan 07 '14 at 22:19
- 
                    I've suggested you an implementation for that random number generator functionality, but update your answer with more code so we can help you out. – João Pinho Jan 07 '14 at 22:39
1 Answers
0
            
            
        You need to use
Math.floor(1 + Math.random() * 10)
Math.random() generates a random number between 0 and 1 (except) [0,1[. Here further info about Math.random(): http://www.w3schools.com/jsref/jsref_random.asp
var c = 120;
window.addEventListener("load",function(){
   document.getElementById('btnRandom').addEventListener("click",function(){
        //this code goes inside click event function
        var b = c + Math.floor(1 + Math.random() * 10);
        document.getElementById('results').innerHTML= "random: " + b;
   }, false);
}, false);
<div id="results"></div>
<input type="button" id="btnRandom" value="Random"/>
And a JSFiddle: http://jsfiddle.net/TRSZj/
Regards.
 
    
    
        João Pinho
        
- 3,725
- 1
- 19
- 29
- 
                    1
- 
                    You may want to be a bit more specific about what `Math.random()` does. Your current statement implies that `11` is a possible result. – Niet the Dark Absol Jan 07 '14 at 22:20
- 
                    True! I've heard that a lot here at SO, never had any trouble with their content dough.. I mainly use it to check things about CSS properties, and JavaScript Native... but that's not my only source :) , with so many sources of info, most of the times I complete the lack of info with knowledge from books. – João Pinho Jan 07 '14 at 22:29
- 
                    
- 
                    Nice... Guess I've been living under a rock... Nice source will follow your advice for sure! – João Pinho Jan 07 '14 at 22:33
- 
                    
- 
                    But I need to know how to have you click a button, and it adds between 1-10 to the total _c_. preferable that total is a variable...and I should be able to use document.getElementById('#id').innerhtml=""; to show "You have _c_ objects" – user2936538 Jan 08 '14 at 23:10
- 
                    1hmmm, you put: var b = candy **+** .... :( you should have put a **+=** instead of a **+** – user2936538 Jan 13 '14 at 23:48
