Check that box

The checkbox field type on our custom request forms feature is acting up.  And by ‘acting up’ I mean ‘a major part of the advertised functionality doesn’t work at all’.  Acting up sounds better.

When an admin is setting up their form, they can choose the field type, add a label, and choose if it should be a required field to submit the form.  The checkbox type wasn’t recognizing the required tag- end users could just submit the form without choosing a checkbox.

Easy fix, right- just check for input[type=checkbox]:checked.length (I know that doesn’t work as typed, don’t worry- just shorthand).  If it === 0, return false.  But there were a couple complications.  Besides my own incompetence, for once.

The feature was coded back in 2003 and is a mixup of php and js- with the js validation checks being generated by (and depending on variables pulled from a database by), quite a bit of php code.  The other main issue is that there’s a different checkbox-driven field type admins can add- a ‘copy self on form’ option.  We didn’t want to include that with the validation on a required checkbox field, as it’s technically a different type.

As usual, I’m sure my answer wasn’t the best.  Or the prettiest.  But it seems to work (and I’ll try to pretty it up a bit before release).  We use the php variable (pulled from the db) to set the ‘required’ property on the field (php print the result of a conditional on the variable- if required, $required = ‘required’, else, $required = ”).  Then, we use the same php variable to add a class to the element’s label.  That way, I can use js to check if the element has the ‘required’ class.  If so, we do the :checked.length check.  That way, we’re only checking the correct set of checkboxes.

A roundabout way to do a simple task, but when you don’t know the fields that the form will include, it becomes a bit more complex.  Now let’s make it pretty…

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s