JonSnow
JonSnow

Reputation: 335

jQuery - Renaming and renumbering (counting) elements

I have a list of table rows and these tr's have numbered classes for some reason (e.g. leg-1, leg-2). It is already possible to delete tr's with the same given class from within this context.

After deleting I need to rename the remaining tr's and here's my problem.

Example: I have

<tr class="leg-1"></tr>
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-3"></tr>
<tr class="leg-3"></tr>

Now I delete leg-2 out of this context. So remaining are:

<tr class="leg-1"></tr>
<tr class="leg-1"></tr>
<tr class="leg-3"></tr>
<tr class="leg-3"></tr>

So as soon as I delete leg-2 , both of the tr's with class="leg-3" have to be renamed to be class="leg-2", so that it comes out like this again:

<tr class="leg-1"></tr>
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-2"></tr>

How can this be done??

Thx for any help!

FIDDLE

http://jsfiddle.net/Lynkb22n/2/

Upvotes: 1

Views: 72

Answers (1)

jyrkim
jyrkim

Reputation: 2869

I extended your existing remove leg button handler code, by adding an update part for table rows once a leg part of the table has been removed. I hope you find the code okay. Fiddle

Btw, this was the first time I have used a containing selector with jQuery, so I find this question cool :-)

 $(document).on("click", "#segment-table .delete_this_leg", function () {
    var rows_to_delete = $(this).parent().parent().parent().attr('class').slice(-1);
    $("tr.leg-" + rows_to_delete).remove();
    var cntAbreiseSegments = $('.legX').length / 3;
    if (cntAbreiseSegments < "2") {
          $('#addSegment').show();
    }

    var  legNro = 0;

    //select all tr elements that which class attribute value
    //contains text: 'leg-'
    $('tr[class*="leg-"]').each(function () {

        $elem = $(this);        
        var elemClass = $elem.attr("class");

        //remove current classes
        $elem.removeClass();

         var legClasses = ""; 

        //element has class divider  
        if (elemClass.indexOf('divider') > -1 ) {
            legClasses = "divider ";
        } //element has class legX, and is not divider
        else if (elemClass.indexOf('legX') > -1 ) {

            legClasses = "legX ";

        } else {//the row with leg text visible

            var text = "leg-" + legNro;

            $elem.find("b").html(text);       
        }

        legClasses = legClasses + " leg-" + legNro; 

        //add updated classes
        $elem.addClass(legClasses);

        //add by one legNro if divider is found
        if (elemClass.indexOf('divider') > -1 ) {
             legNro += 1;
        }       

    });

});

Upvotes: 1

Related Questions