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
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.
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.
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With