Jean Pierre
Jean Pierre

Reputation: 211

updating page with jquery renders javascript function useless?

I have this page where the user select an item and a php file will return a table with a few buttons on each cell but when I click on it the js function is not called.

this is the js function

$('#deleteRow').on('click',function(evt)
{
    console.log('triggered');

}
);

This is the php echo

echo "
<tr>
  <td>$name</td>
  <td>$startData  $startTime</td>
  <td>$endDate $endTime</td>
  <td id='action-buttons'><button type='button' class='btn btn-primary pull-right'  id='deleteRow' ><i class='glyphicon glyphicon-trash'></i> </button></td>
  <td id='action-buttons'><button class='btn btn-primary pull-right' data-toggle='modal' data-target='#myModal'><i class='glyphicon glyphicon-edit'></i> </button></td>
   <td><label id='1'><input id='check' type='checkbox' name='switch' class='checkbox' $activeBool /><div class='switch' ></div></label></td>
</tr>


";

and this is the way I place it on the page (this is the success function fo the ajax post)

 success: function(result){
               $('#content-table tbody').html(result);

             }
             });

I have no idea why this is happening.

Upvotes: 1

Views: 41

Answers (2)

bytesarelife
bytesarelife

Reputation: 414

You are registering the click event on something that doesn't exists yet.

Try this:

$(document.body).on('click','#deleteRow',function(evt)
{
    console.log('triggered');
});

Update:

As ratiorick mentioned, if you have a same id name and you want to get the handle of the one that you actually clicked, you can do something like this:

$(document.body).on('click','button[id^=delete]',function(evt)
{
    console.log('triggered');
});

'button[id^=delete]' basically says that every button whose id stars with delete.

Upvotes: 2

ratiorick
ratiorick

Reputation: 736

You have a few issues.... 1 is that you are using an ID - in a place where you should be using a class... Change "#deleteRow" to ".deleteRow" - you could just bind the event handler in the success callback function like so update the HTML TO this ( you should only use ID if there is 1 element ) otherwise use a class...

Update the HTML - ( also update the rest of these duplicated IDs )

  <td id='action-buttons'><button type='button' class='btn btn-primary pull-right deleteRow' >

And then attach the event handler in the callback function

success : function(result){
    $('#content-table tbody').html(result);
    $('.deleteRow').on('click',function(evt){
        console.log('Is it working now?'); 
    });
} 

Upvotes: 0

Related Questions