Forum Moderators: open

Message Too Old, No Replies

Checkbox validation

         

toltec75

4:47 pm on Sep 13, 2004 (gmt 0)

10+ Year Member



I have 10 possible values and the name of each checkbox is music[].

How do I validate that at least one checkbox is checked?

I tried to use radio boxes validation:

var noChoice = true;
for(i=0;i < document.music.length;i++)
{
if (document.music[i].checked)
noChoice = false;

}
if(noChoice)
{
alert("...error...!");
return false;
}

but it didn`t work!

Thank you!

Bernard Marx

6:14 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member




---html---

<form onsubmit = "return validate(this)" ..blah..>

---script---

function validate(form)
{
var boxes = form.elements['music[]'];
var checked=false, box, k=0;

while(box=boxes[k++])
{
if(box.checked);
checked = true;
break;
}
return checked;
}

toltec75

8:25 pm on Sep 13, 2004 (gmt 0)

10+ Year Member



I can`t get it to work!

I have to use that validation in between many other validations for other fields such as...

<script language="javascript">
<!--

function validInput (form)
{
reg1 = new RegExp("^[A-ZCCŽŠÐa-zccžšd]{4,}");
testing1 = reg1.test(form.user.value);
if (! testing1) {
alert("Username is not valid!");
obrazac.pretplatnik.focus();
return false;
}


reg4 = new RegExp("^[A-ZCCŽŠÐa-zšðèæž0-9]{5,}");
testing4 = reg4.test(form.password.value);
if (! testing4) {
alert("Password must have min. 5 characters!");
form.lozinka.focus();
return false;
}

else
{

return true;
}
}

-->
</script>

How could I get it to work in between those 2 RegExp objects?

Bernard Marx

11:28 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Make the function into one that takes a collection of elements as it's argument, then returns true or false. It can then be used repeatedly in the main validation function for any collection of checkable form elements that you need to see if at least one is checked.

I've made the function simpler..


function hasChecked(collection)
{
var elm, k=0;
while(elm=collection[k++])
if(elm.checked)
return true;
return false;
}

eg:


...
if(!hasChecked( form['music[]'] ) )
alert("Must check at least one")

toltec75

10:01 pm on Sep 14, 2004 (gmt 0)

10+ Year Member



it`s OK! thanx a lot!