JQuery click to Call Function Using a for Statement to Repeat a Dice Roll

JQuery click to Call Function Using a for Statement to Repeat a Dice Roll

 

This example shows how to use JQuery update the web page with results of calling a Javascript function that computes a single die roll for a hard coded number of repetitions using the Javascript “for” statement. The JQuery click method is used to initiate the rolls. The web browser console has report of the processing in the code. For beginners learning Javascript and JQuery.

Lines 15 starts the code block for a JQuery click event method. It selects the #clickToRoll elementon line 66. On line 18 it calls the getDiceRolls() function and assigns to the diceRollValue variable. Line 21 then updates the #helloResults element’s HTML content using the JQuery html method.

The getDiceRolls() function uses a for loop block, lines 31 to 40 to repeat 5 times. In the loop the totalOfRolls variable accumulates the values of each of rolling a single dice.

Line 42 of the getDiceRolls() function returns the totalOfRolls variable.

The getDiceRolls() function is an example of a function having no arguments bur returning a value.

There are a number of console.log lines that will give you a tracing of the processing in the web browser console window.

The \\t seen on lines 32, 35 and 30 is how you express the tab character for plain text output. The web browser console is plain text.

Sample Console Output On Ready

Sample Console Output

Sample Console Output On Click

Sample Console Output

Testing to See If It Works

Open a web browser console window supports the console object for this example. In that console window you will see messages from the Javascript to help you understand what code is being executed.

If your console window was not enabled when you opened this page, then enable and refresh/reload this page to see again.

JQuery Page for Latest Version Download and CDN