Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

If checkbox is not clicked these 2 inputs need values

Status
Not open for further replies.

murphyhg

Technical User
Mar 1, 2006
98
US
I am trying to write some Javascript to determine if a check box is select and if it is not then the 2 input boxes must have values. It is not working. No error messages but nothing is returned.

<script type="text/javascript" language="JavaScript">
<!--
function checkCheckBoxes(form) {
if (
form.IsComment.checked == false &&
form.ChoiceValues.length == 0 || form.ChoiceValues.value == null &&
form.ChoiceStrings.length == 0 || form.ChoiceStrings.value == null)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
} else {
return true;
}
}
//-->
</script>

<input type=submit name="Action" value="Add Question" onClick="checkCheckBoxes(this);">
 
Remove the "onclick" from the submit button, and add the following to your form element:

Code:
<form ... [!]onsubmit="checkCheckBoxes(this);"[/!]>

The "this" in the context of the submit button refers to the button itself, not the form. While you could have used "this.form", the onsubmit handler is the correct way to go.

Hope this helps,
Dan



[url=http://www.coedit.co.uk/][COLOR=#00486F]Coedit Limited[/color][/url][COLOR=#000000] - Delivering standards compliant, accessible web solutions[/color]

[tt]Dan's Page [blue]@[/blue] Code Couch
[URL unfurl="true"]http://www.codecouch.com/dan/[/URL][/tt]
 
You should also change your "if" statement to be:

Code:
if (!form.IsComment.checked && (form.ChoiceValues[!].value[/!].length == 0 || form.ChoiceStrings[!].value[/!].length == 0))

Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Question!
Is there any benefit testing with:
Code:
form.choiceValues.value.length == 0[code]
as opposed to
[code]form.choiceValues.value == ''

???
The form fields should never really have a null value so I always checked if it was == ''.

At my age I still learn something new every day, but I forget two others.
 
Testing .length==0 is better m/c performance-wise; =="" is better (keyboard) operational-wise. At the end, not much.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top