Validating php multiple-value checkbox form element with javascript

In php a multiple-value form element such as checkbox is named suffixed with a set of square brackets. For example,

My commonly used colors are:

To validate these kind of checkboxes’ using javascript is little tricky. While on the other hand, having a single checkbox without multiple-value selection it would have been straight forward, something like this:

Considering multiple-value selection the document.myform[].color.checked or document.myform[].color.length would throw javasript error. To make it work as expected the javascript code in your validate_form function will need some changes. Here we go.

In line 3 of modified function above we use powerful eval function to evaluate the string passed to it. The eval function accepts any valid piece of javascript code and returns output value. In the passed code string to eval function we write normal (parent to child access) algorithm to access the elements property (and its element) of myform object which is a property of our web page (document) object.

One thought on “Validating php multiple-value checkbox form element with javascript

  1. I want to a code which check the validation of different fields.
    Here if i do not fill the first two then it is impossible to leave comment.
    Like this.

Leave a Reply

Your email address will not be published. Required fields are marked *