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)
You can call a function on button click to print the value like this
<input type="button" id="btnSearch" value="Search" onclick="GetValue();" />
<p id="message" ></p>
JS
function GetValue()
{
var myarray= new Array("item1","item2","item3");
var random = myarray[Math.floor(Math.random() * myarray.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}
JS Fiddle Demo
Use Random function of javascript to generate a random number between upper and lower limit of your array. Then use
myarray[Math.round(Math.random() * (myarray.length - 1))]
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).
http://jsfiddle.net/McKxp/
JS:
var arr = ["foo","bar","baz"];
function getItem(){
document.getElementById("something").innerHTML = arr[Math.floor(Math.random() * arr.length)];
}
HTML
<div id="something"></div>
<input type="button" onclick="getItem()" value="Click me"/>
Try this one:
HTML:
<input type="button" click="randomize()" value="Click me" />
JS:
function randomize(){
var myarray = new Array("item1", "item2", "item3");
var randomId = Math.floor((Math.random()*myarray.length));
var randomItem = myarray[randomid];
alert(randomItem);
}
Here is an example:
http://jsfiddle.net/kUgHg/2/
The steps are:
Create a button element and give it an ID:
<button id="button1">Show random item</button>
Get a reference to the button in your script:
document.getElementById("button1");
Compute a random index in your array based on the array length:
Math.floor(Math.random() * 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:
button.onclick = function() { … }
All in one:
var button = document.getElementById("button1");
var myarray = ["a", "b", "c", "d"];
button.onclick = function() {
alert(myarray[Math.floor(Math.random() * myarray.length)]);
};