I am trying to populate Radio buttons with JavaScript. What I have is two Radio buttons that when the page loads will display a random city next to them. So instead of saying "Desitination1" next the a radio button, it needs to say one of the cities below, and must pull different cities each time the page loads. Any help would be appreciated!
if you want them to be truly different every time you reload the page you will have to set a cookie or something, but the following guarantees randomness (a part of random being that repitition is possible)...
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
<head>
</head>
<body onload="city1()">
<form name="surveyForm">
<fieldset>
<legend>I would rather vacation in:</legend>
<label>
<input type="radio" name="pollRadio" id="optRadio1" value="" />
<span id="optSpan1"></span>
</label>
<label>
<input type="radio" name="pollRadio" id="optRadio2" value="" />
<span id="optSpan2"></span>
</label>
</fieldset>
</form>
<script type="text/javascript">
var myVacations = ["Athens", "Madrid", "Tokyo", "Honolulu", "Sydney", "London", "Oslo", "Moscow", "Kingston", "Acapulco", "Brasilia", "Lima", "Chicago", "Toronto", "Cairo", "Egypt", "Capetown"];
function city1() {
var dest1=myVacations[Math.floor(Math.random()*myVacations.length)]
var dest2=myVacations[Math.floor(Math.random()*myVacations.length)]
while (dest1==dest2){
dest2=myVacations[Math.floor(Math.random()*myVacations.length)]
}
document.getElementById("optSpan1").innerHTML=dest1
document.getElementById("optSpan2").innerHTML=dest2
}
</script>
</body>
</html>
Bookmarks