youvegotwood
08-18-2008, 11:57 PM
Hi I'm having a hard time making a check box mandatory, I can make text entry fields mandatory no problem but am having a hard time with a check box.
<form action="transact.dll" method="POST" onSubmit="return validate(form)" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate(frm) {
if (frm.checkbox.value.checked)
{
alert("Please agree to our Terms and Conditons.")
frm.checkbox.focus()
return false
}
}
//-->
</SCRIPT>
I know I'm missing something really simple here I just can't figure out what it is...
binaryWeapon
08-19-2008, 12:47 AM
Corrected code:
<form action="transact.dll" method="POST" onSubmit="return validate(form);" name="form">
<input type="checkbox" name="checkbox" id="checkbox" value="1"> I hereby agree to all Terms and Conditions</a>
<input type="submit" value="Submit">
</form>
<SCRIPT LANGUAGE="JavaScript">
<!--
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
//-->
</SCRIPT>
Changes are marked in red.
- I added a few semicolons throughout just because its a bit more syntactically correct
- checkbox.value.checked should be checkbox.checked==false. It will always return a boolean (true/false) so you can't use the if(checkbox.value.checked) method.
- I took out the frm.checkbox.focus(); because there's really no point in focusing a checkbox. Its not like a text field where you have to click to get the cursor there, there's really not a big reason to focus it. If you want you can put that back in, though.
VIPStephan
08-19-2008, 01:30 AM
Even more corrected code:
<script type="text/javascript">
// <![CDATA[
function validate(frm) {
if (frm.checkbox.checked==false)
{
alert("Please agree to our Terms and Conditions.");
return false;
}
}
// ]]>
</script>
rangana
08-19-2008, 04:30 AM
@VIPStephan,
I thought cdata were only a mandatory for XHTML for the page to validate. :confused:
I suppose it should work well without cdata if the page was served with HTML doctype.
And yes, language is a deprecated attribute.
VIPStephan
08-19-2008, 03:11 PM
I thought cdata were only a mandatory for XHTML for the page to validate. :confused:
It is but I’d say in HTML it doesn’t hurt either. In any way it’s better than the HTML comments that are commonly used.
youvegotwood
08-25-2008, 08:15 PM
Thanks guys! That worked like a charm!