Wednesday, January 5, 2011

Delegates in JQuery

The listener of click event wont be listened by the straight approach like the following when you dynamically create the html part and append to the existing elements of a page.

$('#btnEdit').click(function(){

Say, when a row is appended to an existing table element(With a hyperlink in each row to edit the row item) on a click event, the edit row event of the row cant be managed by the following syntax

$('#btnEdit').click(function(){

Here you play with delegate.

See, on click of an html button control, you are adding a row to the existing table (Id="") at the end of the rows like the following.





$('#btnAdd').click(function(){
$('#TableOne > tbody:last').append('<tr><td>F13</td><td><a href="#" class="lnkEdit">Edit</a></td></td><td><a href="#" class="lnkRemove">[X]</a></td></tr>');
});

The row contains three TD elements, which includes a hyperlnk to edit the row and another to delete the added row.

$('#btnAdd').click(function(){
$('#TableOne > tbody:last').append('<tr><td>F13</td><td><a href="#" class="lnkEdit">Edit</a></td></td><td><a href="#" class="lnkRemove">[X]</a></td></tr>');
});

Edit event can be captured here as following

$('#TableOne').delegate('a.lnkEdit', 'click', function(){

$(this).closest("tr").each(function() {
var tr = $(this);
var column = 1;
$('td', tr).each(function(index, value) {
var td = $(this);
alert(td.text());
column++ ;
var txttd = $("input:text", td).each(function(){
alert($(this).val());
});
});
});


The Delete click can be handled here

 $('#TableOne').delegate('a.lnkRemove', 'click', function(){
$(this).closest("tr").remove();
});



Can add the content into the DIV like this
$('#dvEdit').after('<b>ADDING HERE</b>');
});

Here follows the HTML part

<table id="TableOne" class="TableOne" cellspacing="1" border="0" bgcolor="#f1f1f1">
<tr> <td>
<input type="text" class="txtbox" /></td>
<td> F12</td>
<td> F13</td>
</tr> <tr>
<td> <input type="text" class="txtbox" /></td>
<td> F22</td>
<td> F23</td>
</tr> <tr>
<td> <input type="text" class="txtbox" /></td>
<td> F32</td>
<td> F33</td>
</tr> </table>
<div id="dvEdit" class="dvEdit"></div>
<input type="button" value="Get" id="btnGet" class="btnGet"/>
<input type="button" value="Add" id="btnAdd" class="btnAdd" />

Just a CSS tip too, to beautify the table.

$('#TableOne tr').each(function() {
var tr = $(this);
$('td', tr).each(function() {
var td = $(this);
$(this).addClass("tdbg");
$(this).attr("width", "200px");
});
});

No comments: