faqts : Computers : Programming : Languages : JavaScript : Forms : Radio buttons

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

10 of 14 people (71%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How do I check that all radiobuttons in a form have an item checked?

Aug 18th, 2005 20:45
Mauricio Urso, Keith Rockhold, Here is my own code


<script type="text/javascript" language="javascript">
	function valida_questionario(){
		var elementos = document.getElementsByTagName("input");
		var radios=Array();
		var j=0;
		var k=0;
		var flag=false;
		for(i=0;i<elementos.length; i++){
			if (elementos[i].type == "radio"){
				radios[j]=elementos[i];
				j++;
			}
		}
		var encontrados=conta_grupo_radios(radios);
		for(i=0;i<encontrados.length;i++){
			flag=false;
			for(j=0;j<encontrados[i];j++){
				if(radios[k].checked==true)
					flag=true;
				k++;
			}
			if(!flag){
                                //include here any alert if wanted
				return false
			}
		}
		return true;
	}
	function conta_grupo_radios(radios){
		var j=0;
		var k=1;
		var encontrados=Array();
		for(i=1;i<radios.length;i++){
			if(radios[i].name!=radios[i-1].name){
				encontrados[j]=k;
				j++;
				k=1;
			}
			else{
				k++;
			}
		}
		encontrados[j]=k;
		return encontrados;
	}
</script>
<form method="post" action="teste.php" onSubmit="return 
valida_questionario();">
<!-- Include here all your radio inputs -->
</form>