Ensuring at least one form element has been used

D

DoomedLung

Hey,

I'm currently developing an online work brief, where the user has to
enter details regarding the project into a form. I've come to a section
in the form where the user has the option of selecting between two
checkboxes and an input element. I have to ensure that at least one of
the checkboxes have been checked or that the input element is not
empty. I've come up with this function:

function validateMedia(){
var count = 0;
if(document.workBrief.mediaOnline.checked){
count++;
}
if(document.workBrief.mediaPrint.checked){
count++;
}
if(document.workBrief.mediaOther.value != ""){
count++;
}
if(count > 0){
return true;
}else{
alert('Please choose at least one media option');
return false;
}
}

I'm sure there is a more effiecient way of writing this.

You thoughts are much appriciated :)
 
W

web.dev

DoomedLung said:
Hey,

I'm currently developing an online work brief, where the user has to
enter details regarding the project into a form. I've come to a section
in the form where the user has the option of selecting between two
checkboxes and an input element. I have to ensure that at least one of
the checkboxes have been checked or that the input element is not
empty. I've come up with this function:

function validateMedia(){
var count = 0;
if(document.workBrief.mediaOnline.checked){
count++;
}
if(document.workBrief.mediaPrint.checked){
count++;
}
if(document.workBrief.mediaOther.value != ""){
count++;
}
if(count > 0){
return true;
}else{
alert('Please choose at least one media option');
return false;
}
}

I'm sure there is a more effiecient way of writing this.

You thoughts are much appriciated :)

Here's my version of refactoring:

javascript:

function validateMedia()
{
var myForm = document.forms["workBrief"];

if(myForm.elements["mediaOnline"].checked ||
myForm.elements["mediaPrint"].checked)
{
return true;
}

if(myForm.elements["mediaOther"] != "")
{
return true;
}

alert('Please choose at least one media option');

return false;
}

Assuming your html is something like the following:

<form name = "workBrief" onsubmit = "return validateMedia()">
<input type = "checkbox" name = "mediaOnline">
<input type = "checkbox" name = "mediaPrint">
<input type = "text" name = "mediaOther">
<input type = "submit" value = "Submit">
</form>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top