3

I want to hide all the tr except the first one. then i want each tr to appear when someone will click on add link.

How can i hide all the table row except the first one.

here is my http://jsfiddle.net/Nx4cD/9/

$( document ).ready(function() {
$(".add").click(function() {
    var
    $this = $(this),
    $row = $this.closest("tr"),
    $rowIndex = $row.index();
    $row.next().show("medium").find("td").eq(0).html($rowIndex+2);
});
$(".delete").click(function() {
    $(this).closest('tr').hide();
});

});

2 Answers2

5

You can exclude the first element using .not() method:

$('table tbody tr').not(':first').hide();

And for selecting the next hidden tr element you can use .nextAll() and :hidden selector:

var $row = $this.closest("tr").nextAll(':hidden').first();
Ram
  • 143,282
  • 16
  • 168
  • 197
  • thanks. http://jsfiddle.net/Nx4cD/10/ so, is this ok. or can be optimized. i also want to display s.no for each row. don't want to do by writing directly in html. i managed to do it using index(). is there any better method. and how can i diplay s_no for first row also –  Oct 13 '13 at 22:48
  • i would like to display s_no also for each tr. can you help me with that –  Oct 13 '13 at 22:52
  • @user2847429 You are welcome, the ideal method is creating/removing `tr` elements. You can either use `.clone()` method or create the `tr` and `td` elements using JavaScript. – Ram Oct 13 '13 at 22:57
  • ok. what about displaying serial no value for each tr element –  Oct 13 '13 at 23:03
  • @user2847429 Check this http://jsfiddle.net/6rHks/, this works but I don't recommend it, please check this questions, http://stackoverflow.com/questions/2362982/jquery-dynamically-create-table-tr-td-or-etc-and-append-attributes, http://stackoverflow.com/questions/4789923/adding-content-to-a-table-row-tr-with-javascript – Ram Oct 13 '13 at 23:07
  • If you want to create many elements dynamically it would better to use a templating library like Mustache or Handlebars. You are welcome. – Ram Oct 13 '13 at 23:09
  • actually i am not creating any row. i am working on a django project using formset. server is sending me around 50 rows. on the front end side i need to hide it appearing all at once. and then displaying it one by one –  Oct 13 '13 at 23:11
  • Well. In that case using delete option is not necessary http://jsfiddle.net/ZrRPq/ – Ram Oct 13 '13 at 23:14
0

Try use JQuery index here:

$(".delete").click(function() {
        var parentRow = $(this).closest('.table > tbody > tr');
        if(parentRow.index() != 0){
            parentRow.hide();
        }  
    });
Mohamed AbdElRazek
  • 1,654
  • 14
  • 17