I am trying to develop a plugin for jQuery. This is my first plugin, and I am stuck in the initial phase.
I need to do following things: I need to find the “add row” link from the table and bind to the click event. When the link is clicked, it should add a new row by cloning the existing template row. Initially the template row is hidden.
Following is the HTML.
<table id='grid1'>
<tr>
<td><a href='#' id='add_row'>Add New Row</a></td>
</tr>
<tr>
<td>
<table id='data_table'>
<tr><th>Col1</th><th>Col2</th><th>Col3</th></tr>
<tr><td>Data1</td><td>Data2</td><td>Col3</td></tr>
<tr id='template_row'>
<td><input type='text' /></td>
<td><input type='text' /></td>
<td><input type='text' /></td>
</tr>
</table>
</td>
</tr>
</table>
And my jQuery so far:
(function($) {
$.extend($.fn, {
editableGrid: function() {
function addRow() {
//code to clone here but i need the instance of main table here ie grid1
}
this.find('#add_row').bind("click",addRow);
}
});
})(jQuery);
Going on from your current code:
Notes
bind()over usingclick()here"a.add_row"is better than just".add_row")thisrefers to a jQuery object containing all matched elements, soclick()binds all of them in one step.thisrefers to an individual DOM element (i.e. the clicked link) – it is not a jQuery object here!falsefrom theclickfunction to prevent the browser default behavior$to denote that they contain a jQuery object