Click to See Complete Forum and Search --> : checking radiobuttons
demolay
05-25-2004, 01:49 PM
i want to prepare a form validation javascript..
there are some radiobuttons and at least one of them should be selected. i want javascript to check this and if non of them is selected, it should warn the user with an alert message...
theBody44
05-25-2004, 02:24 PM
<script>
function check(){
var ok = false;
for (i = 0; i<document.forms[0].bob.length; i++){
if (document.forms[0].bob[i].checked){
ok = true;
break;
}
}
if (!ok){
alert("Select a radio button");
}
else{
//Continue with more validation stuff
}
}
</script>
<form>
<input type="radio" name="bob">
<input type="radio" name="bob">
<input type="radio" name="bob">
</form>
<span onClick="check()">HELLO</span>This script should get you on the right track.
demolay
05-25-2004, 02:38 PM
i am not advanced to understand and use this script :(
is there a more easy one?
theBody44
05-25-2004, 02:40 PM
Post some of your code with the radio buttons and I can show you how to get started on it.
Vladdy
05-25-2004, 02:46 PM
Just set one to be checked by default - no JS needed.
demolay
05-25-2004, 02:48 PM
<input type="radio" name="radiobutton" value="1">
1
<input type="radio" name="radiobutton" value="2">
2
<input type="radio" name="radiobutton" value="3">
3
<input type="radio" name="radiobutton" value="4">
4
it goes to 11...
only one of them must be selected.
demolay
05-25-2004, 02:50 PM
Originally posted by Vladdy
Just set one to be checked by default - no JS needed.
i know thanks, but i am trying to learn js :)
Vladdy
05-25-2004, 02:52 PM
Then your first lesson should be:
Do not use scripting where it does not belong
theBody44
05-25-2004, 02:55 PM
var ok = false;
for (i = 0; i<11; i++){
if (document.forms[0].radiobutton[i].checked){
ok = true;
break;
}
}
if (!ok){
alert("Select a radio button");
}
This should work for you. Just place it somewhere inside your form validation function that you're creating. The only difference might be whether or not you have a form. If your radio buttons are not in a form, then you won't need the "forms[0]" part. If they are in 1 of many forms, you can changes "forms[0]" to just the name of the form that holds them. Granted, Vladdy is right, you can very, very easily set a default radio button to checked and not even have to worry about this.
demolay
05-25-2004, 03:10 PM
i dont know why but it doesnt work. instead i tried to do somthing like this:
if(!form.radiobutton.checked) {
alert("Not checked");
return false
}
but it even gives alert when i check one of them...
theBody44
05-25-2004, 03:17 PM
That's because it's an array of elements. So when you check to see if the array is checked, you will get "undefined" back. Therefore, since (not-undefined) points to "true", it executes the alert. You have to check each one individually, and for that you need a loop. Either find a good tutorial on control statements or create a default/checked option. That will be your best bet.:)