Small JavaScript problem

Soldato
Joined
28 Feb 2006
Posts
3,819
Location
London
I was wondering if anyone can tell me where I have gone wrong with the following code, the answer should be England, and if you select it, it should say 'you selected England correct!' however it always displays the message which its only supposed to display if you get it wrong.

<script type="text/javascript">
<!--
function checkAnswer ()
{

var oSelCountry = document.getElementById("country");
var index = oSelCountry.selectedIndex;

if (oSelCountry == "England")
{
alert("You selected" + oSelCountry.options[index].text + " correct!");
}
else
{

alert("You selected" + oSelCountry.options[index].text + " wrong!");
}
}

//-->
</script>

</head>
<body>
<p>what country borders Scotland?</p>
<select name="country" id="country">
<option >Ireland</option>
<option >Wales</option>
<option >England</option>
<option >don't know</option>
</select>
<input type="button" value="send" onclick="checkAnswer()">

Any help appreciated.
 
a) no form tags
b) no values asssigned to the select options
c) the javascript is probably not addressing the select object properly
d) not pulling the selected value from the select object properly

give the following code a try:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
function CheckAnswer()
{
// address the select object 'country' in form 'question'
var oSelCountry = document.forms['question'].elements['country'];

// get the value of the selected option
var answer = oSelCountry.options[oSelCountry.selectedIndex].value;

// set the variable 'response' according to the selected answer
var response = (answer == 'England') ? 'correct!' : 'wrong!';

// display the alert
alert('You selected ' + answer + ' : '+ response);
}
</script>
</head>

<body>
<p>what country borders Scotland?</p>
<form id="question" method="post" action="">
<select name="country" id="country">
<option value="null">Select a country</option>
<option value="Ireland">Ireland</option>
<option value="Wales">Wales</option>
<option value="England">England</option>
<option value="unknown">Don't know</option>
</select>
<input type="button" value="send" onclick="CheckAnswer()">
</form>
</body>
</html>
 
Back
Top Bottom