The other day I was using jQuery chained methods and realized that I had no idea how or why this works. I figure it would be very nice if I could create my own for checking required fields and submitting a form. For sake of simplicity I am using jQuery in some parts of this example but this can be modified to do away with jQuery. I wanted to do something like this
mySubmitter(theForm).CheckRequired().SubmitForm();
First I needed to understand how this could work and it turns out it is quite simple. Since everything in JS is an object, a method can return itself, so the chaining of methods is basically just short hand for something like this:
var ret = mySubmitter(theFormID); ret = ret.CheckRequired(); ret = ret.Submit();
Since the method returns itself any changes made to the attributes of that object can be used in the next call. So for our Submitter we can do something like this:
function mySubmitter(form){ var run = false; var TheForm = form; this.CheckRequired = function(){ run = true; //CHECK ALL FIELDS SET run TO FALSE IF ANY IS EMPTY return this; // this is what makes chaining work } this.SubmitForm = function(){ if(run){TheForm.submit(); //this is a jQuery method } else{ alert('There are missing fields in your form');} return this; // this is what makes chaining work } }
So for a complete example we have something like this:
The Form
<form id="myForm" action="somescript.php"
method="POST" name="myForm" enctype="multipart/form-data">
<label for="name">Name</label>
<input type="text" class="required" name="name" id="name"/>
<label for="email">Email</label>
<input type="text" class="required" name="email" id="email"/>
<label for="phone">Phone</label>
<input type="text" class="required" name="phone" id="phone"/>
<div id="mySubmit">Submit</div>
<!--I use a div to capture the submit event easily with jquery-->
</form>
The Javascript
$(document).ready(function(){ $('#mySubmit').click(function(){ new mySubmitter($('form[name=myForm]')).CheckRequired().SubmitForm(); }); }); function mySubmitter(form){ var run = false; var TheForm = form; this.CheckRequired = function(){ run = true; // Loop through all fields and change the style if needed $('.required').each(function(i){ // remove the highlight if this is not the first time $(this).removeClass('missing'); if($(this).val() == '') { run = false; // there are missing fields $(this).addClass('missing'); // this highlights the missing fields } }); return this; } this.SubmitForm = function(){ if(run){TheForm.submit(); //this is a jQuery method } else{ alert('There are missing fields in your form');} return this; } }
As you can see it would be very easy to add more methods like AddWaitAnimation or HideSubmitButton to protect the user from double clicking the submit button.
Leave a Reply