JavaScript Validation

Hey,

I am trying to work out a way to validate the following page: http://www.loumolloy.com/testing.php

On page load a survey will appear, you will see “Step1…2…3” at the top. Now users should not be able to get to the next step unless they have filled in all the fields… In this case it is simply radio buttons for question 1 and 2.

I have put together the following function to validate the boxes but it does not work properly, if i select female i get the wrong error. It’s like it only validates correctly if i check the first radio button?

Anyway, this is the function:


function validate_page_1()
{
	if(document.getElementById('input-1').checked != true)
	{
	 alert('You missed out question 1.');
	} 
	if(document.getElementById('input-2').checked != true) {
	 alert('You missed out question 2.');
	} else {
	document.getElementById('page-1').style.display='none';
	document.getElementById('page-2').style.display='block';
	}
}

If you view source on the page you will see that on this line:

 <input type="submit" class="button-next right" name="btnnext" value="" onclick="validate_page_1()"/>

I trigger the validation, and it does pick it up but i don’t know why it’s not doing it properly…

Can anyone help?

Thanks again

I’ve changed the function to this just making it more readable…


function validate_page_1()
{
	if(document.getElementById('gender').checked != true)
	{
	 alert('You missed out question 1.');
	} 
	if(document.getElementById('age').checked != true) {
	 alert('You missed out question 2.');
	} else {
	document.getElementById('page-1').style.display='none';
	document.getElementById('page-2').style.display='block';
	}
}

Can anyone see where the problem is?

IDs should be unique. I noticed that you reuse IDs on the radio buttons.

So, you can either specify a unique ID for each radio button and check through each one individually, or use getElementByName to get the set of radio buttons returned as an array.

I’ve used a function like this in the past to check if a radio button has been selected within a set with the same name:

    function isRBchecked(elementName){
        var jumper = document.getElementsByName(elementName);
        var elementValue = false;
        for(var j=0;j<jumper.length;j++){
            if(jumper[j].checked){
                elementValue=true;
            }
        }
        return elementValue;
    }