Mood Swing » Nostalgic

Journal » Post

pngfix

Recently I was working on a site which required multiple groups of checkboxes, since it was a site that gathered data through a survey... don't ask what site it is. At first I though of PHP to handle the validation but the code will take way too long and if we need to go back to the page it would be hard to cache the data already passed. Hence my javascript solution; the advantage of this is that we validate the form first before anything is passed to the server, the obvious disadvantage is it wont work if javascript is disabled.

The idea is to cache all the group names into an array and check each group if a value was selected; then do the necessary prompts and what not. so first up is the function to check our array:

 
function inArray(array,elemento){
    for(var 
i in array){ if(array[i]==elemento) return true;}
    return 
false;
}
 

Now the function to check the form, I fire this function with the onsubmit event, and passing the form name to it like so:

 
onsubmit
="return validate('form_name_here')"
 

And the function...

 
function validate(formname) {
    
    var 
els document.forms[formname].elements;
    var 
radios = new Array;
    var 
0;
    
    for (var 
0elel els[x]; x++) {
        if ((
el.type.toUpperCase() == "RADIO") && (!inArray(radiosel.name))) {
            
radios[i] = el.name;
            
i++;
            var 
checked = -1;
            for (var 
0radioradio = eval('document.forms[formname].' el.name '[y]'); y++) {
                if (
radio.checkedchecked 1;
            }
            
            if (
checked == -1) {
                
alert("Please answer all questions");                        
                return 
false;
            }
            
        }
    }
    return 
true;
}
 

Talkback

No reactions

Post a reaction



 


*Enter the characters displayed on the image below on the verify image text box above. Note that this is case sensitive.

captcha image

 
Back to top
contact