Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
508 views
in Technique[技术] by (71.8m points)

Click table rows to select checkbox using jQuery

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to select the checkbox of a row inside the table, we will first check whether the type attribute of the element we are targetting is not a checkbox if it's not a checkbox than we will check all the checkboxes nested inside that table row.

$(document).ready(function() {
  $('.record_table tr').click(function(event) {
    if (event.target.type !== 'checkbox') {
      $(':checkbox', this).trigger('click');
    }
  });
});

Demo


If you want to highlight the table row on checkbox checked than we can use an if condition with is(":checked"), if yes than we find the closest tr element using .closest() and than we add class to it using addClass()

$("input[type='checkbox']").change(function (e) {
    if ($(this).is(":checked")) { //If the checkbox is checked
        $(this).closest('tr').addClass("highlight_row"); 
        //Add class on checkbox checked
    } else {
        $(this).closest('tr').removeClass("highlight_row");
        //Remove class on checkbox uncheck
    }
});

Demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...