« Populating Select Element Option Lists with option_switcher.php | Main | Using prototype.js For Faster JS Development and AJAX »
April 14, 2009
Using JavaScript Validation For Mandatory Form Elements
When forms are built using the interface_functions.php
functions a mandatory red asterisk is added to the markup but hidden in the HTML this can be used to flag mandatory elements and also for validation checking:
<script type="text/javascript"> var els = new Object(); els['start'] = 'Start Time'; els['duration'] = 'Duration'; els['purpose'] = 'Purpose of booking'; els['course_code'] = 'Course Code'; els['booker_name'] = 'Your Name'; els['email1'] = 'Your email address'; function check_mandatory(els){ var popper = new Array(); for(i in els){ if($(i).value == ''){ popper.push("<strong>" + els[i] + "</strong>"); $(i).style.border = '1px solid red'; } } if(popper.length > 0){ poppy("<p>You must provide the following information:</p><ol><li>" + popper.join('</li><li>') + "</li></ol><p>[Click in this box to hide it.]</p>"); return false; } else{ return true; } } </script>
Call the function with an onsubmit=""
event handler:
<form
class="content nothing_added"
style="width: 900px; text-align: left; height: 320px; vertical-align: top; clear: both; display: block;"
action="booking_details_doozer.php"
method="post"
id="booking_details_form"
onsubmit="return check_mandatory(els)"
>
To mark the required form elements as mandatory use the following code (make sure your JS is called after all the relevant form elements have been rendered, i.e. at the bottom of the page):
<script type="text/javascript"> for(i in els){ $(i + '_mandatory').style.display = 'inline'; } </script>
Tags: Lightweight PHP Web Application Framework
Posted by pj at April 14, 2009 02:29 PM