Forum Moderators: open

Message Too Old, No Replies

form validation

get users to check box before submitting

         

HelenDev

2:56 pm on Dec 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I need a small snippet of code to make users check a checkbox before they can submit the form.

My js isn't hugely advanced so I usually use Dreamweaver to generate form validation code, but I can't seem to make it work for checkboxes, only text fields.

Can anyone help?

Fotiman

6:04 pm on Dec 16, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



In your form onsubmit event handler, call a function to check the value. That function should return true if checked, false if not. So

<script type="text/javascript">
function isChecked( checkboxId )
{
var cbox = document.getElementById(checkboxId);
if(!cbox ) return false;
if( cbox.checked )
{
return true;
}
return false;
}
</script>

<form onsubmit="return isChecked(myCheckBox)">
<input type="checkbox" id="myCheckBox" name="myCheckBox">
<input type="submit" name="submit" value="Submit">
</form>

I think that would do it.

DrDoc

7:42 pm on Dec 18, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You still need to verify that the box is checked on the server side as well.

kaled

12:06 am on Dec 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try this...

<form onsubmit="return this.checkboxname.checked">

Provided the checkbox is located within the html form it should work.

Kaled.

Fotiman

2:41 pm on Dec 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month




Try this...

<form onsubmit="return this.checkboxname.checked">

Provided the checkbox is located within the html form it should work.

But of course, that will simply confuse the end user as there is no warning given or anything to signify why the form isn't submitting. But separating it out, you could add alert messages or whatever to notify the user to check the box.

le_gber

3:20 pm on Dec 19, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or you could disable the submit button if the box is not checked, and enable it once checked

Of course server side checking is also necessary if you want to be 100% sure that the box has been checked.

Finally if you use javascript to disable the submit button originally (on page load for example) you can be sure that people with JS disable will still be able to submit the form.

hope this helps