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â
