...

View Full Version : How to make a checkbox mandatory



youvegotwood
08-19-2008, 12:57 AM
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">&nbsp;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, 01: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">&nbsp;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, 02: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, 05: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, 04: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, 09:15 PM
Thanks guys! That worked like a charm!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum