0

I'm using bootstrap table in my view, and table rows are dynamically created, and after they are created I would like to attach a .onclick event to my rows so in case someone clicks on the row I might highlight it, I tried it and tested it, and I couldn't figure out how to solve this.

Here is my code:

1.) First, try - absolutely bad because keeps attaching events on my row, after few clicks there is 5-6-7 alerts popup..

@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>

     $('#TableItems').click(function (e) {
            $('#TableItems tr').click(function (e) {
                alert("Clicked!");
            });
        });

</script>

2.) Second try - also not good because view is rendered and tr are not rendered yet so probably, onclick event can not be attached because when I'm clicking on it nothing is happening

$('#TableItems tr').click(function (e) {
                alert("Damn");
         });

Here is my table

<div class="table-responsive" id="myTable">
   <table class="table table-striped  jambo_table bulk_action">
     <thead>
       <tr class="headings">
          <th class="column-title">Title </th>
        </tr>
     </thead>
    <tbody id="TableItems"></tbody>
   </table>
</div>
Rajan Mishra
  • 1,178
  • 2
  • 14
  • 30
Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • You need [event delegation](https://learn.jquery.com/events/event-delegation/) - e.g. `$('#TableItems').on('click', 'tr', function() { ...` –  Sep 14 '17 at 12:47
  • @StephenMuecke You comments are allways awesome mate! It's easy to recognize that you are full of knowledge, It's my pleasure to read you comments! Thanks one more time! One more question is, for each of this tr I generated Id = "something" and how I could I get that Id value from this e object, is that even possible? – Roxy'Pro Sep 14 '17 at 12:55
  • Yes - `var id = $(this).attr('id');` but why are you giving `tr` elements an `id` attribute (does not really make sense) –  Sep 14 '17 at 12:57
  • @StephenMuecke Because in that dynamically generated table I'm keeping list of customers, each customer has an Id, and by clicking on a row I want to fill another table with some other informations.. – Roxy'Pro Sep 14 '17 at 13:00
  • You really should be using `data-*` attributes for that - e.g. `` (and accessing if with `$(this).data('customerid');`) –  Sep 14 '17 at 13:02
  • @StephenMuecke why should I do that? That's some convention / best practice or ? I thought it does not matter what kind of attribute I choose there, I guess because we'r talking about Id I should use id attribute.. – Roxy'Pro Sep 14 '17 at 13:06
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/154449/discussion-between-stephen-muecke-and-roxypro). –  Sep 14 '17 at 13:07

1 Answers1

0

You can use .on() for this

$('#TableItems').on('click', 'tr', function (e) {
    alert("Damn");
});
Super User
  • 9,448
  • 3
  • 31
  • 47