简体   繁体   中英

Datatables issue: How can I click a checkbox and then highlight the row and vice versa?

I have a table row and want to get a cell in the table like:

<tr>
    <td><input type="checkbox"id="delete" value="1"></td>
                        <td id="rowid">1</td>
                        <input 
                        <td>2</td>
                        <td>test</td>
                        <td>email@gmail.com</td>
                        <td>1</td>
                        <td>5</td>
                        <td>2018-12-31 09:28:29 </td>
        </tr>

I have jquery code:

$(document).ready(function() {
    var table = $('#clients').DataTable();

    $('#clients tbody').on( 'click', 'tr', function () {
        $(this).toggleClass('selected');
        var _element = $(this).find('input[type=checkbox]');
        var checkboxStatus = _element.prop('checked'); //true or false
        _element.prop('checked',!checkboxStatus); // If checkbox is 
        //checked, turn it to uncheck and if is unchecked, check it
} );
    } );

    $('#button').click( function () {
        alert( table.rows('.selected').data().length +' row(s) selected' );
    } );
} );

But now when I click the checkbox it doesn't get checked and the 'checked' class is not added to the checkbox input.

I want that if i click the whole that then the checkbox becomes checked. This now works, but when I check the checkbox the becomes highlighted but the checkbox isn't checked.

Add an event listener on click to your checkbox stopping the propagation of the event to the row, and then toggle the class to the closest row of the checkbox:

 $(document).ready(() => { $('#clients tbody').on('click', 'tr', function(e) { $(this).toggleClass('selected'); var _element = $(this).find('input[type=checkbox]'); var checkboxStatus = _element.prop('checked'); _element.prop('checked', !checkboxStatus); }); $('#clients tbody').on('click', 'input[type=checkbox]', function(e) { e.stopPropagation(); $(this).closest('tr').toggleClass('selected'); }); }); 
 .selected { background: red; } table { border-collapse: collapse; border-spacing: 0; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="clients"> <tbody> <tr> <td><input type="checkbox" id="delete" value="1" /></td> <td id="rowid">1</td> <td>2</td> <td>test</td> <td>email@gmail.com</td> <td>1</td> <td>5</td> <td>2018-12-31 09:28:29 </td> </tr> </table> 

ps in your pasted snippet, you have an invalid input tag wrapping a td

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM