Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery and adding row to table

Tags:

jquery

I have the following jquery code.

var destTable = $("#numbers");
$(document).ready(function() {
  $("#btnAdd").click(function() {
   //Take the text, and also the ddl value and insert as table row.
   var newRow = $("<tr><td>hi</td></tr>");
   $("#numbers").append(newRow);
  });
});

What I would really like is to store a reference to an element once and then use it from there on it.

The code above add's a row to my table as expected but if I use. $(destTable).append(newRow) or destTable.append(newRow) nothing happens could anyone shed any light on this for me?

Thanks

like image 895
RubbleFord Avatar asked Jul 01 '09 07:07

RubbleFord


People also ask

How do you add a row to a table?

You can add a row above or below the cursor position. Click where you want in your table to add a row or column and then click the Layout tab (this is the tab next to the Table Design tab on the ribbon). To add rows, click Insert Above or Insert Below and to add columns, click Insert Left or Insert Right.

How do you insert new row at a certain index in a table in jQuery?

The task is to insert a new row in that table at a certain index using JQuery. Approach: Store the table column value <td> element into the variable. Then use eq() and after() method to insert the row in a table.

How do I add a row to a table in button click?

To add a row, define a variable that keeps the count of the total number of that now exists in the table. Then we will use the jQuery “click” event to detect a click on the add row button and then use the . append() method of jQuery to add a row in the table.

How do you add a row in HTML?

The insertRow() method inserts a new row at the specified index in a table, in this example, the first position (the beginning) of a table with id="myTable". Then we use the insertCell() method to add cells in the new row.


1 Answers

Keep the reference inside document.ready:

$(document).ready(function() {
  var destTable = $("#numbers");
  $("#btnAdd").click(function() {
   //Take the text, and also the ddl value and insert as table row.
   var newRow = $("<tr><td>hi</td></tr>");
   $("#numbers").append(newRow);
  });
});

The point of document.ready is to wait for the DOM to be ready; if you try doing $('#numbers'); outside of it (and the code does not appear after the element in the document) the DOM will not have yet created this element so you won't have a proper reference to it.

Once you do this, you should be able to do:

destTable.append(newRow);

Inside the click function. As a last note, however, it is a common and accepted practice to preface variables that represent jQuery sets with a $. So this is best:

var $destTable = $("#numbers");
like image 195
Paolo Bergantino Avatar answered Sep 23 '22 17:09

Paolo Bergantino