Click to See Complete Forum and Search --> : Radio Buttons


bim269
03-19-2004, 04:55 AM
i am doing a question and answer site, now i have four radio buttons to a queation and each question comes out on a page.
i want to check for
1. if the user did not choose any of the option
2. if the correct answer is choosen to display msg "correct answer"
3. if the correct answer is not choosen, to display msg "incorrect answer,see Tip for correct answer"

this is the code i wrote to check if the user has chosen an answer but it is not working as expected

<script language='javascript'>
function checkForm(Form1){
if (!Form1.question[1].checked) {
var choice = confirm("Do you want to choose an answer?");
if (choice) {
return false;
}else {
myForm.action = "Quest1s.html";
}
}
}
</script>
pls i need help urgently

buntine
03-19-2004, 06:27 AM
You have to use the document object.

function checkForm(Form1){
if (!document.Form1.question[1].checked) {
var choice = confirm("Do you want to choose an answer?");
if (choice) {
return false;
}else {
myForm.action = "Quest1s.html";
}
}
}


Though, these days its better to use the getElementsByName() function. This will return an array of all the elements on the page which have the name set as the given value.

function checkForm(Form1){
if (!document.getElementsByName("question")[1].checked) {
var choice = confirm("Do you want to choose an answer?");
if (choice) {
return false;
}else {
myForm.action = "Quest1s.html";
}
}
}


Regards,
Andrew Buntine.

wingman8
03-19-2004, 01:24 PM
Here is a simple function to get the value of the selected radio button:

function getRadioVal(radioObj)
{
var value = "";

if (!radioObj.length)
{
if (radioObj.checked) value = radioObj.value;
}
else
{
for (var i = 0; i < radioObj.length; i++)
{
if (radioObj[i].checked)
{
value = radioObj[i].value;
break;
}
}
}

return value;
}


Just pass in your radio button object like so:

var selectedVal = getRadioVal(document.Form1.question);

Then you can compare "selectedVal" to whatever to determine correctness of the answer. If it's an empty string then they didn't select anything.