Saturday, July 7, 2012

jQuery: Binding events dynamically for easy form validation

So often times you have a big form where you need to validate each field individually. Using the $.each () function provided in the jQuery library you can easily loop through an array of Ids and bind events to each one. If you want to do it manually you will have to use a closure (see here).

So lets say you have a big form and a list of text boxes on that form. You probably want to check for several things but you may first of all want of your fields to check for length. So lets make a form that will have error sections after fields. In here we can give the user messages about each text box.


<form type='post' action=''>
<table cellpadding='10'>
    <tr>
        <td>First Name:</td>
        <td><input type='text' name='first_name' id='firstname' /></td>
        <td><span id='firstnameerrors'></span></td>
    </tr>
    <tr>
        <td>Middle Initial:</td>
        <td><input type='text' size='3' name='middle_name' id='middlename' /></td>
        <td><span id='middlenameerrors'></span></td>
    </tr>
    <tr>
        <td>Last Name:</td>
        <td><input type='text' name='last_name' id='lastname' /></td>
        <td><span id='lastnameerrors'></span></td>
    </tr>
</form>







Now for the JavaScript: we need to make an array for each piece of data we need (make sure that these arrays are parallel). We need an array to hold the IDs of each textbox, the IDs of each error span, and finally the things to validate for on each textbox. I made a max length array, and we will count the length of the current value of each of the text boxes. We will then compare against values in the list and display either the count or an error message.



<script type='text/javascript'>
    $(document).ready(function() {
        // section for active validation
        var arrFields = ['#firstname', '#middlename', '#lastname'];
        var errorFields = ['#firstnameerrors', '#middlenameerrors', '#lastnameerrors'];
        var minLengths = [1, 0, 1];
        var maxLengths = [20, 1, 30];
                      
        // This is the special loop with an automatic closure:
        $.each(new Array(arrFields.length),function(i) {
          
            // pull out each thing we need from the iterator.
            var field = arrFields[i];
            var error = errorFields[i];
            var maxlen = maxLengths[i];
          
            //console.log("Binding: " + field + " to error:" + error);
          
            $(field).bind("keyup", function() {
                console.log("firing for: " + field);
                var f = $(field).val();
                var lenField = f.length;
                console.log("length: " + lenField);
              
                $(error).empty().append(lenField + "/" + maxlen);
                if(lenField > maxlen) {
                    $(error).empty().append("Too long!");
                    }
                }); // end bind
              
        });// end loop
      
        // section for submission validation
    });
  
</script>



Now, every time you type into any of the fields in the ID array, an event will fire for each one, providing whatever dynamic validation you have programmed in.

Remember you need to jQuery libraray to make this work. I would recommend using google's CDN for this:


        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

By the way, here is a full length example using the jquery $.each() loop on my github.


No comments:

Post a Comment