PDA

View Full Version : Was any checkbox checked.


Vladimir
09-08-2002, 07:50 PM
I need to check if at least one checkbox was checked before submition of the page. Any Javascript function I can use? All checkboxes have the same name (like an array).

umm
09-08-2002, 08:22 PM
not the prettiest function around but it works fine for one checkbox group. Excuse the indentation.

I should add that I haven't had time to refine this script. Revisiting it now, I can see some potential for improvment - still it does work.


<script language="javascript" type="text/javascript">
<!--

function val(form){

var booleanSwitch=true
var i=-1

if(form.email.value==""){
alert("Email Address is a required field")
form.email.focus()
booleanSwitch=false
return false

} else
if(booleanSwitch !=false){
while(!form.os.checked){
i++
if(i==form.os.length){
alert("You must select an Operating System")
return false

} else
if(form.os[i].checked){
return true
}
}
}
}
// -->
</script>


And the form...

<form action="javascript: alert('Submission Successful')" onsubmit="return val(this)">
Email Address
<br>
<input type="text" name="email" id="emailAddress">
<br>
Operating System
<br>
<input type="checkbox" name="os" value="mac">Mac
<br>
<input type="checkbox" name="os" value="win95">Win95
<br>
<input type="checkbox" name="os" value="Win98">Win98
<br>
<input type="submit" value="Send">
</form>

hth

Vladimir
09-09-2002, 02:09 AM
thanks a lot!