• Blogs (9)
    • đŸ“± 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • jQuery: $(this.form) and this.form ...

    Blogs20112011-05-20


    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"
       ondblclick="$(this).removeAttr('readonly').css('border-width','2px');"
       value="<?=htmlspecialchars($row['title']);?>"
       style="width:100%; border:0px solid #e0e0e0;" />
     <input type="hidden" name="id" value="<?=$row['id'];?>" />
    </form>

    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;
     $.ajax({
      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 HTML element.
    • this.form refers to the form, which this is inside. it is a JavaScript Object. It equals to: $(this).closet(‘form’).get(0);
    • 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: () this.form.id.value; which equals: $(this.form.id).val() or: 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’