Inserting a new Row into a viewPanel (any table) using jQuery

This is a short and sweet blog post showing how to programmatically add a new line into a table using jQuery.

Introduction

I am playing around with some column ordering and I want to add some dummy data to a table – rather than go to the trouble of doing it on the back end I decided to do it using jQuery so that i can easily change the values using Firebug

The .before() function

The .before() function inserts a set of HTML “before” the selected DOM element. It has a companion .after() function which unsurprisingly adds HTML after a DOM element.

Inserting a new row
I want to add my new line as the top row of this table

nr1

and I do this by:

  1. Selecting the first child in the viewPanel (class=.xspDataTable) tbody
  2. adding the new row before it
$('.xspDataTable tbody')    //select the tbody within the viewPanel
        .children(':eq(0)') //select the first child therein
        .before("<tr class='marky'><td>9</td><td>3</td><td>1</td><td>7</td></tr>")

Now why do I do that you ask? – good question. As I found out it turns out that the viewPanel has a TR in the header before the TBody – so if I select the first row in the table then I do not get the first “data row” so I go for the first child in the TBODY which is the TR element representing the first row I am looking for.

Here is what we get – short and simple

nr2

The code change looks like this

nr3becomes

nr4

 

 

Advertisement

One thought on “Inserting a new Row into a viewPanel (any table) using jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s