Finding the next input (parent?) Using jQuery

I have a checkbox inside the table, and when you click on it, it will change the background color accordingly so ...

$("#table tr td :checkbox").bind("click change", function() {
    $this = $(this); // cache the jquery object
    if($this.is(':checked')) { $this.closest('tr').css('background-color', 'lightyellow'); }
    else { $this.closest('tr').css('background-color', '#fff'); }
});

This works fine, however, I decided that I would like to go better, so at any point in the table that you click, it will check the box and highlight the row.

I tried using this code, but it does not work unfortunately:

$("table tr").bind("click", function() {
    $(this).parents("tr").find(":checkbox").attr('checked');
});

And here is the HTML code (remote redundant material to improve readability ...

<td>Name</td>
<td>Description</td>
<td><input type="checkbox"></td>

Any help would be greatly appreciated, thanks!

+3
source share
3 answers

, , - . - , . , , find() .

.live, , .

, , . ( , tr tbody, )

$("table>tbody>tr").live("click", function() {
    $(this).find(":checkbox").attr('checked', 'checked');
});

, -

$("table>tbody>tr").live("click", function(ev) {
        var $checkbox = $(this).find(":checkbox");
        //check to see we have not just clicked the actual checkbox
        if ( !$(ev.target).is(':checkbox') ){
            $checkbox.is(':checked') ? $checkbox.removeAttr('checked')
                                     : $checkbox.attr('checked', 'checked')
        }
 });
+2

:

$(this).parents("tr").find(":checkbox").attr('checked');

:

$(this).parents("tr").find(":checkbox").attr('checked', 'checked');

, , checked, .

+2

, .

$("table tr").bind("click", function() {
    $(this).find(":checkbox").attr('checked', 'checked');
});

jQuery Docs on Attributes .


redsquare, , .parent("tr") .

+1

Source: https://habr.com/ru/post/1715171/


All Articles