javascriptjqueryhtmltwitter-bootstrapjquery-on

jQuery on 'click' not triggering after change to a bootstrap table


situation

I am using bootstrap to render a table based on values in an array of objects. I have a select which has a jQuery on ('change') method attached so that when an item from the list is selected, a new table is rendered based on the selected value.

the table uses bootstrap collapse to show/hide rows from the table when the top row is clicked. the last item in the row has a glyphicon arrow which shows the row can be folded/unfolded as the picture below shows

collapse with glyphicon

I am using the below jQuery to toggle the icon

$('#tog').on('click', function() {
  console.log("tog clicked");
  $(this).find('span').toggleClass('glyphicon-arrow-up glyphicon-arrow-down');
});

so far I have this all working as shown with this fiddle http://jsfiddle.net/vgfb74u0/

Problem

the issue I am facing is that when a new table is rendered based on the selected item the jQuery that changes the glyphic does not trigger so when the table unfolds the icon remains the same.

I have put in some console.log at the start of the method and I never see it firing. so to my newbie eyes the click event is never triggered.

I'm surprised that i've managed to get this far and at a loss to what the issue might be so any help, pointers or advise is most welcome!


Solution

  • You need to manually bind events to any dynamically created element, or let jQuery do that for you.

    Changing

    $('#tog').on('click', function() {});
    

    To

    $('html').on('click', '#tog', function() {});
    

    Will tell JavaScript to delegate the event to any #tog that's created inside the <html> element.