简体   繁体   中英

change row color of jquery datatable if row is checked?

I have a jquery dataTable ( this is link ) in each row there are a checkbox! I whish that when the checkbox is checked the row color change!

I try in this way: tableCode;

<table id="tabellaOrdinaFarmaci" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Codice Farmaco</th>
            <th>Nome Farmaco</th>
            <th>Quantità</th>
            <th>Quantità di alert</th>
            <th>Stato</th>
            <th></th>
        </tr>
    </thead>
</thead>
<tbody>
    <?php foreach ($query as $row): ?>
        <tr> 
            <td><?php echo $row->aic; ?></td>
            <td><?php echo $row->denominazione ?></td>
            <td><?php echo $row->quantita; ?></td>
            <td><?php echo $row->alert; ?></td>
            <td><?php echo $row->stato; ?></td>
            <td>  <input type="checkbox" name="radiog_lite" id="<?php echo $row->aic; ?>" class="css-checkbox" />
                <label for="<?php echo $row->aic; ?>" class="css-label"></label>
            </td>
        </tr>
    <?php endforeach; ?>
</tbody>

jQuery code:

 jQuery(document).ready(function() {
    jQuery('input').click(function() {
        jQuery(this).parents("tr").css('background-color', 'yellow');
    });

});

This code color only the rows that have an index odd!If I inspect the element from the browser background-color: yellow is added to all rows! Help me thanks in advance! I think that the problem is bootstrap dataTable.

if you want only that row to change color for which checkbox is checked then you have to use closest() and use change event for it:

jQuery('#tabellaOrdinaFarmaci input:checkbox').change(function() {
       if(this.checked)  // check if checkbox checked then change color of row
          jQuery(this).closest("tr").css('background-color', 'yellow !important');
    });
jQuery('#tabellaOrdinaFarmaci input:checkbox').change(function() {

       if(this.checked)  // check if checkbox checked then change color of row

          jQuery(this).closest("tr").css('background-color', 'yellow !important');

    });

convert angulerjs

Use closest() to find the parent <tr>

Your elements are getting appended later to the DOM, use event delegation ,

jQuery(document).ready(function() {
    jQuery(document).on('click','input',function() {
        jQuery(this).closest("tr").css('background-color', 'yellow');
    });

});

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