user142617
user142617

Reputation: 386

Jquery Insert a table row after the selected table row

I am trying to insert a table row after the row the user has selected:

Here is the fiddle:

http://jsfiddle.net/tonymaloney1971/ykxgy6dj/2/

So, if the user selects Product 0, we insert a new after Product 0.

At the moment I am trying insertAfter but it is deleting the next table row?

$('#tableBody tr').on('click','button', function() { var insertData = "

"; var insertAfter = $(this).closest('tr');

        if($(this).text()  =='+')
        {
            $(this).text('-');
            //I would like to insert a new table row underneath the current selected table row?
            insertAfter.insertAfer(insertData);
        }
        else
        {
            $(this).text('+');
        }
    });      

Thanks

Upvotes: 0

Views: 2505

Answers (2)

Steve Saporta
Steve Saporta

Reputation: 4881

Ahmet Can Güven's answer is very close. I had to make some minor changes for it to work. The documentation for insertAfter helps us understand why.

$(document).ready( function () {            
$('#List li').hide();

$('#tableBody tr').on('click','button', function() {
    var $insertData = $("<tr><td><ul><li>Q</li><li>W</li><li>E</li><li>R</li><li>Y</li></ul></td></tr>");
    var $insertAfter = $(this).parent();

    if($(this).text()  =='+')
    {
        $(this).text('-');
        //I would like to insert a new table row underneath the current selected table row?
        $insertData.insertAfter($insertAfter);
    }
    else
    {
        $(this).text('+');
    }
});                              

});

Upvotes: 0

Ahmet Can G&#252;ven
Ahmet Can G&#252;ven

Reputation: 5462

You need to practice on dom traversing

$(document).ready( function () {            
    $('#List li').hide();

    $('#tableBody tr').on('click','button', function() {
        var insertData = "<tr><td><ul><li>Q</li><li>W</li><li>E</li><li>R</li><li>Y</li></ul></td></tr>";
        var insertAfter = $(this).parent();

        if($(this).text()  =='+')
        {
            $(this).text('-');
            //I would like to insert a new table row underneath the current selected table row?
            insertAfter.append(insertData);
        }
        else
        {
            $(this).text('+');
        }
    });                              
});

Upvotes: 0

Related Questions