Black
Black

Reputation: 89

How do I insert a "remove button" to every table row when inserting a new row using javascript/jQuery

I would prefer to do it using javascript but if jQuery is easiest, then I will use that instead. I just don't understand jQuery very well. What I have currently for my HTML table is:

<table id = "liftTable" border="1" rules="rows">
<caption><b>Today's Workout</b></caption>
<tr>
 <th align="left" width="150">Lift Name</th>
 <th align="left" width="90">Weight (lbs)</th>
</tr>
<tr>
  <td>Bench Press</td>
  <td>2000</td>
  <td><input name="btnRemoveItem" type="button" id="btnRemoveItem" value="Remove Lift" onclick="removeListItem(this)"/></td>
</tr>
<tr>
 <th align="left">Total:</th>
 <td class="sum">0</td>
</tr>
</table>

That table has a sample already there showing how I want every new row to be set up. Here is my "Add Row" javascript:

function addTableRow(){
var iteration = 1;
var table = document.getElementById("liftTable");
var rowCount = table.rows.length - 2;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = document.getElementById("Form1").value;
cell2.innerHTML = document.getElementById("numOfSets").value;
var bt = document.getElementById("btnRemoveItem");
cell3.appendChild(bt);
}

The biggest issue is when I try create "var bt = document.getElementById("btnRemoveItem");" and try to insert that into cell3. I don't really know how to accomplish this any other way. Thanks for any help.

Upvotes: 2

Views: 1505

Answers (2)

citizenslave
citizenslave

Reputation: 1418

You could always create a new element with document.createElement("input"). cloneNode() is already doing this anyway, but it gives you the flexibility to set the ID manually and to instantiate the input element without regard for whether or not there are any live examples in the DOM currently. That's vanilla JS. jQuery just has you wrap a $() around that if memory serves, and that only allows you to use jQuery to alter it and insert it instead of vanilla JS.

Upvotes: 1

Ryan Ransford
Ryan Ransford

Reputation: 3222

Browsers usually don't like it when you try to add the same exact element object to the DOM more than once in different places.

Try this instead and note that you may have to deal with multiple elements on the page which have the same element Id:

var bt = document.getElementById("btnRemoveItem").cloneNode();

Upvotes: 3

Related Questions