Click table rows to select checkbox using jQuery

前端 未结 5 1618
难免孤独
难免孤独 2020-12-01 03:07

As I didn\'t find any question asked before, on how to toggle checkbox on click of a table row, so I would like to share my approach to this...

5条回答
  •  春和景丽
    2020-12-01 03:48

    This question was useful to me but I had an issue with the previous solution. If you click on a link in a table cell, it will trigger the checkbox toggle. I googled this and I saw a proposition to add a event.stopPropagation() on the links of the table, like this:

    $('.record_table tr a').click(function(event) {
      event.stopPropagation();
    });
    

    This solution was a bad idea because I had some jquery bootstrap popover on a link of the table...

    So here is a solutions that fits me better. By the way as I'm using bootstrap 2.3, the highlight of the line is made by adding the "info" class to the tr. To use this code, you just need to add class="selectable" to the table tag.

    $(".selectable tbody tr input[type=checkbox]").change(function(e){
      if (e.target.checked)
        $(this).closest("tr").addClass("info");
      else
        $(this).closest("tr").removeClass("info");
    });
    
    $(".selectable tbody tr").click(function(e){
      if (e.target.type != 'checkbox' && e.target.tagName != 'A'){
        var cb = $(this).find("input[type=checkbox]");
        cb.trigger('click');
      }
    });
    

    You will probably want to be more specific with the test condition, for exemple if you have other inputs in the row.

提交回复
热议问题