William Jiang

JavaScript,PHP,Node,Perl,LAMP Web Developer – http://williamjxj.com; https://github.com/williamjxj?tab=repositories

jQuery: $(this.form) and this.form …

While processing dynamic forms, I found something is easy to be confused, as: this.form, this.form.id, $(this.form.id) etc.

My dynamic form likes this:

<form method="post" action="<?=$this->url;?>" id="t_<?=$row['id'];?>">
 <input name="title" readonly="readonly"
   style="width:100%; border:0px solid #e0e0e0;" />
 <input type="hidden" name="id" value="<?=$row['id'];?>" />

What I want to do are: when double click, make the form editable, and when its content changes, call AJAX to update DB, and refresh the form. The following uses jQuery as well as JS to traverse the form to do the implementment.

$('form input[name="title"]').bind('change', function(tid) {
 var form = this.form;
  type: $(form).attr('method'),
  url: $(form).attr('action'),
  data: $(form).serialize(), 
  dataType: 'json',
  success: function(data) {
    // refresh this form with 'data'.
 return false;

It works fine, the following is a summary of the work, focusing on this.form:

  • this keyword is inside the ‘change‘ event, it represents the <input type=”text”> HTML element.
  • this.form refers to the form, which this is inside. it is a JavaScript Object. It equals to:
  • this.form.id refers to a HTML element inside this form which name is ‘id’:
    <input type=”hidden” name=”id”>
    this.form.id returns a Javascript Object, it equals to:
    $(this.form input[name=’id’])[0]
    or: document.getElementById(‘id’) //when there is an attribute id=”id”
  • to traverse the form, use:
    this.form; //DOM
    $(this).closet(‘form’); //jQuery Object
  • to get the form id attribute:
    $(this.form).attr(‘id’); //jQuery Object
  • to get DOM element ‘id‘ value: (<input type=”hidden” name=”id”>)
    this.form.id.value; which equals:
    document.getElementById(‘id’).innerHTML; //when there is an attribute id=”id”
  • to get any form’s DOM element:
    this.form.‘element name’
    to access any form’s jQuery object:
    $(this.form).‘jQuery Selector’

One response to “jQuery: $(this.form) and this.form …

  1. Julius 02/14/2013 at 4:00 pm

    Hi William. I have a shopping cart application and would like to use this code to add a product to the cart without leaving the page. What modifications need to be made?

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: