简体   繁体   中英

Add selected class to table row when click on that row

i have table

<table width="100%" border="0" cellspacing="0" cellpadding="0" class="activity_tab">
    <tr id="list_1">
        <td><span class="new_act">Folder files Created</span>
        </td>
        <td>2013-06-24 02:11 am</td>
    </tr>
    <tr id="list_2">
        <td><span class="new_act">Folder ss Created</span>
        </td>`enter code here`
        <td>2013-06-24 02:11 am</td>
    </tr>

and its dynamic table data comes on run time when i click on a row i want to add selected class to that row. after that i have hyper link at top of page

 <li><a href="javascript:void(0);" class="delete">Delete</a></li>

this is my hyperlink now when click on hyperlink the selected row will bhe deleted how can i get the selected row and i have all idea about its deletion but could'nt find any solution...

You can do this -

$('.activity_tab tr').on('click',function(){
  $(this).addClass('selected');
});
$('.delete').on('click',function(){
   $('tr.selected').remove();
});

I would add a class on the selected row. I'm assuming you can only have one selected row at a time, so you'll need to remove any selections when a new row is clicked.

Since your table is dynamic, you'll need to use a delegated event listener to add the selected class. See the documentation of jQuery's on() method for more details on delegated events.

$(document).on('click', 'tr', function(e) {
    $('tr.selected').removeClass('selected'); //clear other selections
    $(this).addClass('selected'); //mark this row as selected
});

$('a.delete').on('click', function(e){
   e.preventDefault(); //stop native link behavior
   $('tr.selected').remove(); //remove selected row
});

Note that the listener that adds the selected class to a row will affect any tr element in the document. If you have other tables on your page, you will need to make the second selector (after the 'click') more specific.

You can try this

$(function(){
    $(".activity_tab tr").click(function(){
        $(this).addClass("red");
    });

    $('.delete').on('click',function(){
       $('tr.red').remove();
    });
});

Demo: http://jsfiddle.net/YNNVr/

You can add selected class to tr on click with following code.

$('.activity_tab').on('click', 'tr', function(){
   $(this).addClass('selected');
});

And if you want to take that one step further, you can use toggleClass instead of addClass , so you can remove the selected class with just another click on the tr .

You can then select all the selected rows and delete them

$('.delete').on('click', function(){
   $('activity_tab .selected').remove();
});

This removes all rows with selected class in the table with activity_tab class.

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