468,505 Members | 1,544 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,505 developers. It's quick & easy.

Ensuring at least one form element has been used

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 :)

Sep 28 '06 #1
1 1229

DoomedLung wrote:
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>

Sep 28 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

72 posts views Thread by Stephen Poley | last post: by
12 posts views Thread by CJ | last post: by
3 posts views Thread by Skippytpe | last post: by
4 posts views Thread by John Fereira | last post: by
6 posts views Thread by drec | last post: by
reply views Thread by NPC403 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.