Please can someone help. I am trying to create a basic button in javascript that when clicked picks a value at random from my array and display it on the screen, each time the button is clicked it should pick a new item from the array. I know how to write the array
var myarray = new Array("item1", "item2", "item3");
I just dont know how to do the button part. Any help would be great. I know it may be easier to do this in jQuery, but I really want to get my head round javascript before I tackle jQuery (please be gentle I am new to this lol)
http://jsfiddle.net/McKxp/
JS:
HTML
Use Random function of javascript to generate a random number between upper and lower limit of your array. Then use
to access a random value from the array.
You can use this link to see hot to generate a random number between a min and max number. (for your case min will always be 0).
Here is an example:
http://jsfiddle.net/kUgHg/2/
The steps are:
Create a button element and give it an ID:
Get a reference to the button in your script:
Compute a random index in your array based on the array length:
Add a
click
event handler to your button that calls the random computation at step 3 and shows it a way you want:All in one:
Try this one: HTML:
JS:
You can call a function on button click to print the value like this
JS
JS Fiddle Demo