0

I understand random numbers and adding numbers, but I don't understand how to add a random number to a number currently displayed. I have a jsFiddle here that shows what I have now, but I want that button to add another random number with each click to the current number displayed.

EDIT: I should clarify that my jsFiddle is clunky and I would like a more efficient solution for my question.

1
  • 1
    Either get or store the number to display and just add the random number to it. Commented Aug 28, 2012 at 23:42

4 Answers 4

1

When setting the randomnumber div you can use

$("#randomnumber").text(($("#randomnumber").text() * 1) + numRand);

where $("#randomnumber").text() * 1 will be 0 when blank or the latest total

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

2 Comments

Do remember to use parseInt() (with the radix) or parseFloat() (just to be sure).
@DavidThomas that's what the *1 is doing, but I'd prefer the parseXXX approach
1

Keep the Sum value in a global variable. Add to that everytime when you generate the new random number.

Jsfiddle sample : http://jsfiddle.net/CsHyW/4/

Comments

1

Why such a convoluted example? If I understand correctly this should work:

http://jsfiddle.net/CsHyW/10/

var max = 13;
var $wrap = $('#randomnumber');
$('#getit').click(function() {
    var num = +$wrap.text();
    $wrap.text(num + Math.ceil(Math.random() * max));
});

2 Comments

+1 for the plus trick. instead of using parseInt is that right ?
yup, + just converts the string to a number.
0

If I understood your question correctly you want to either store all the numbers generated or to add their value into an accumulated variable. Here's a fiddle with both and it will alert the array of numbers as well as the accumulated result.

Solution

Comments

Your Answer

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