Tuesday, February 19, 2013

When jQuery form submission not works , Work arounds.

Let us consider the below form and various ways to do a form submission in client side programming.

1:    
2:  <form id="formId" name="formName" class="form-class" action="" method="post">  
3:  </form>  

Before introducing jquery, the famous but harshful way to access DOM is using the popular getElementByID() method in javascript so accomplish a form submission we can use it like below,

1:    
2:  document.getElementById("formId").submit();  
3:    

Also if there is no id for the form we can still use the form name to do a form submission as below,

1:    
2:  document.getElementsByName("formName")[0].submit();  
3:    

But with jQuery life has become much easier and we can use either form ID in the way we use them to decorate using CSS or either CSS classes to pick elements. Below is how we can do a form submit using form ID

1:    
2:  $("#formID").submit();  
3:    

And we can use the class selectors to access forms as well. This method returns an array of elements which has the same style class. (In our example we have only one element, and it is our form.)

1:    
2:  $(".form-class")[0].submit();  
3:    

Finally we can use elements itself to access themselves. This method will return an array of same elements. (According to our example we only have one element of type "form".)

1:    
2:  $("form")[0].submit();  
3: