I've read several stackoverflow answers related to my problem saying that when you dynamically add a row, the best way to make to new row respond to events is to have a $('.class_name').on('click',function(e) { declaration instead of $('.class_name').click(function() {
That made sense to me so I tried it and it still doesn't work. Nothing happens when I click the inserted link in the inserted row. I've put the code in a JSFiddle here: http://jsfiddle.net/Thread7/osctqotj/
Or pasted below. Here is my HTML
<table>
<tr><td><a href="javascript:void(0);" id="num_1" cnt="1" class="num-link">1</a></td><td>Harry</td></tr>
<tr><td><a href="javascript:void(0);" id="num_2" cnt="2" class="num-link">2</a></td><td>Sally</td></tr>
<tr><td><a href="javascript:void(0);" id="num_3" cnt="3" class="num-link">3</a></td><td>Wally</td></tr>
</table>
<input type='button' id='add-row' value='Add Row'>
<br/><br/>
<input type='text' id='write-rank' curcnt='0' style='width: 15px;'>
and here is my javascript:
$('.num-link').on('click',function(e) {
var cnt = $(this).attr('cnt');
$("#write-rank").attr('curcnt', cnt);
var x = $(this).position();
$("#write-rank").val('');
$("#write-rank").css({top: x.top - 4, left: x.left - 5, position:'absolute'});
$("#write-rank").show();
$("#write-rank").focus();
});
$('#add-row').on('click',function(e) {
add_row_for_new_user('Pablo');
});
function add_row_for_new_user(new_user_name) {
var dis = $(".num-link:first");
var $curRow = $(dis).closest('tr');
$newRow = get_blank_row(new_user_name);
$curRow.before($newRow);
}
function get_blank_row(new_user_name) {
var ret = '<tr><td><a href="javascript:void(0);" id="num_99" cnt="99" class="num-link">0</a></td><td>'+new_user_name+'</td></tr>';
return ret;
}
Any ideas?