Inserting a new Row into a viewPanel (any table) using jQuery
Posted by MarkyRoden on September 9, 2013
This is a short and sweet blog post showing how to programmatically add a new line into a table using jQuery.
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
Inserting a new row
I want to add my new line as the top row of this table
and I do this by:
- Selecting the first child in the viewPanel (class=.xspDataTable) tbody
- 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
The code change looks like this