Dynamic table- add row with event bind
by charlietfl
HTML
<button id="add_row">Add Row</button>
<table cellpadding="0" cellspacing="0" border="1" width="100%" id="tblInventoryItems">
<tr class="tch">
<th class="thc"> </th>
<th class="thc" scope="col">Item</th>
<th class="thc" scope="col">Unit Price</th>
<th class="thc" scope="col">Quantity</th>
<th class="thc" scope="col">Total</th>
</tr>
<tr class="dataRow">
<td>
<img name="DeleteRow_1" alt="Delete Row" class="button_link" src="" /></td>
<td class="ttc">
<input type="text" name="tbTitle_1" class="field_input tbTitle" /></td>
<td class="ttc">
<input type="text" name="tbSalesPrice_1" class="field_input tbSalesPrice" /></td>
<td class="ttc">
<input name="tbQuantity_1" type="text" class="field_input tbQuantity" /></td>
<td class="ttc">
<input type="text" name="tbTotal_1" class="field_input tdTotal" />
</td>
</tr>
</table>
<ul><li>Stripped all ID's from elements other than table</li>
<li>Added class to inputs "tbTtitle", "tbSalesPrice" etc</li>
<li>Added class "dataRow" to first row data</li>
<li>FAKE AUTOCOMPLETE: on keyup takes value and concatenates value+value+value</li>
</ul>
CSS
ul{ margin-top:40px;}
li{margin-top:.5em;}
JavaScript
function fakeAutoComplete(){
var text=$(this).val().toString();
$(this).val(text + text + text);
}
$(document).ready(function(){
// use new classes to setup calc function using live()
$('.tbSalesPrice, .tbQuantity').live('keyup', function(){
var $row=$(this).closest('tr');// all based on parent row
var unitP= $row.find('.tbSalesPrice').val();
var qty= $row.find('.tbQuantity').val();
var total= unitP*qty;
if( total){
$row.find('.tdTotal').val(total)
}
});
// bind fake autocomplete to first row
$('.tbTitle').bind("keyup", fakeAutoComplete )
var numberExistingRows=1;
// use "ADD" button to add new row
$('#add_row').click(function(){
// keep track of number of rows for input names
numberExistingRows++;
// clone a row
var $row= $('.dataRow:last').clone();
// strip previous values and fix names of inputs
$row.find('input').each(function(){
var $input=$(this);// cache this input into jQuery object in lieu of using $(this) in below functions for clarity and performance
$input.val("");// reset value to none
// fix names
var thisInputName=$input.attr('name').split('_')[0] +'_'+numberExistingRows;
$input.attr('name', thisInputName)
});
// bind fake auto complete to new row. SInce using classes now makes it much easier to locate correct input
$row.find('.tbTitle').bind("keyup", fakeAutoComplete ) ;
// for real autocomplete
// $row.find('.tbTitle').autocomplete(// options)
// append to table id=tblInventoryItems
$('#tblInventoryItems').append( $row);
});
});