Anirudha Gupta
Anirudha Gupta

Reputation: 9289

How i can add my td in the table as i want?

 <tbody>
    <tr class="th">
        <td>
            this is a heead
        </td>
        <td>
        </td>
    </tr>
    <tr>
        <td>
            Half Pallets
        </td>
        <td>4 Full Pallet
        </td>
    </tr>
     <tr>
        <td>

        <td>4 Full Pallet
        </td>
    </tr>
</tbody>

Take a look,Suppose i want to add the tr for first tr.th then I want to set them on last tr then first tr.th but how I can do.

If their is multiple tr.th in table then I need to set the tr from last from second tr.th in my case.

Could you show me how I can do this.

thanks

Upvotes: 1

Views: 122

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

Assuming you have some HTML like so:

<table>
    <tbody>
        <tr class="th">
            <td>Some header</td>
        </tr>
        <tr>
            <td>Some data</td>
        </tr>
        <tr>
            <td>Some more data</td>
        </tr>
        <tr class="th">
            <td>Another header</td>
        </tr>
        <tr>
            <td>Some data</td>
        </tr>
        <tr>
            <td>Some more data</td>
        </tr>
    </tbody>
</table>

Then I assume you want the resultant HTML to look like this:

<table>
    <tbody>
        <tr class="th">
            <td>Some header</td>
        </tr>
        <tr>
            <td>Some data</td>
        </tr>
        <tr>
            <td>Some more data</td>
        </tr>
        <tr>
            <td>A new bit of data in a new row</td>
        </tr>
        <tr class="th">
            <td>Another header</td>
        </tr>
        <tr>
            <td>Some data</td>
        </tr>
        <tr>
            <td>Some more data</td>
        </tr>
    </tbody>
</table>

In that case, you could use the following jQuery:

var headerRows = $('tr.th');

if(headerRows.length > 1) {
    var headerRow = headerRows.get(1);
    $(headerRow).before('<tr><td>A new bit of data in a new row</td></tr>');
}
else if(headerRows.length == 1) {
    var headerRow = headerRows.get(0);
    $(headerRow).closest('tbody').append('<tr><td>A new bit of data in a new row</td></tr>');
}
else {
    // no header rows - do nothing?
}

Working DEMO

Or, a fiddle that adds a new row before the next <tr> element with the class th when a <tr> element with the class th is clicked on: Updated DEMO

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

you could do (i intended that you want to add a new <tr> to the end of the table: if the last <tr> has the class th you want to add the new <tr> before the <tr class="th"> :

//get the last tr
var trLast = $('tr:last');
//create a tr to add
var trToAdd = $('<tr>');
//if the last tr has the class th
if(trLast.hasClass('th'){
   //add the new tr before the last
   trLast.before(trToAdd);
}else{
   //add the new tr after the last
   trLast.after(trToAdd);
}

Upvotes: 1

Related Questions