0

I'm generating this HTML on .cs side :

<table>
    <tr>
        <td>Product</td>
        <td>Price</td>
        <td>Destination</td>
        <td>Updated on</td>
    </tr>
    <tr>
        <td>Oranges</td>
        <td>100</td>
        <td><a href="#" class="toggler" zzz="1">+ On Store</a></td>
        <td>22/10</td>
    </tr>
    <tr class="cat1" style="display:none">
        <td></td>
        <td>120</td>
        <td>City 1</td>
        <td>22/10</td>
    </tr>
    <tr class="cat1" style="display:none">
        <td></td>
        <td>140</td>
        <td>City 2</td>
        <td>22/10</td>
    </tr>
     </table>

And by calling the controller with Ajax I add the HTML to the page like this :

$.ajax(
      url:"/MainController/HTMLGenerator",
      success : function (data) {
      $('#mydiv').html(data);
})

I also have this JS code to toggle rows :

$(".toggler").click(function(){

    $('.cat'+$(this).attr('zzz')).toggle();
});

But no matter what I do, I couldn't get the link working. I guess it happens because HTML is generated at the backend. I don't know how to solve this though. Thanks in advance.

jason
  • 6,962
  • 36
  • 117
  • 198
  • 2
    It's because you're attempting to bind the event handler to elements which do not yet exist in the DOM - they're only available *after* the AJAX request completes. To fix this, use delegated event handlers. See the duplicate I marked for more information – Rory McCrossan Jun 20 '18 at 14:51
  • @RoryMcCrossan, would it be logical if I put click event handler inside AJAX call's success part? – jason Jun 20 '18 at 14:58
  • It just worked when I did that :) – jason Jun 20 '18 at 15:02
  • You could do that, but it's not a great idea as you may end up duplicating the event handlers when the AJAX call is next made. It just opens you up to creating more problems – Rory McCrossan Jun 20 '18 at 15:03
  • Also note that `zzz` is not a valid attribute. I'd suggest using `data-zzz="foo"` then `data('zzz')` to retrieve it in jQuery – Rory McCrossan Jun 20 '18 at 15:03
  • I'm making the AJAX call only once. There wouldn't be a problem I suppose. – jason Jun 20 '18 at 15:04

0 Answers0