I am trying to use JavaScript or ASP C# to add rows to a table in form when the user clicks the add row button. I have working code in JavaScript. I want to add the rows with text input boxes inside of the <td></td> tags. The row count is in my code becasue I am attempting to use it to add IDs to each element for use later.
element.innerHTML(<input id="tagcell"+(rowcount+1)+"" type="text"/>);
function addrow() {
var rowcount =
document.getElementById('tbl').getElementsByTagName('tbody').length;
window.alert(rowcount);
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = "";
desccell.innerHTML="";
loccell.innerHTML = "";
Namecell.innerHTML="";
Sigcell.innerHTML = "";
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
Here's how you could do that. (Obviously you can style the text boxes however you want.) Your code added the rows; I just added a textarea in each cell.
function addrow() {
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var rowcount = tableRef.rows.length;
window.alert(rowcount);
var newRow = tableRef.insertRow(tableRef.rows.length);
var textBox = "<textarea></textarea>";
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = textBox;
desccell.innerHTML= textBox;
loccell.innerHTML = textBox;
Namecell.innerHTML= textBox;
Sigcell.innerHTML = textBox;
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
EDIT: Your row count shows the correct number now. (It was only showing 1 each time before.)
function addrow() {
var myTable = document.querySelector('#tbl');
var row = myTable .insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = 'My first cell';
// and so on for other cells
}
p.s. please add "" to all your HTML attributes values. For example
<table id="tbl">
Related
I have a table of rows and a button to delete it in each row.
I can remove a row bot the problem is that I need to update the value deleteRow(nb_of_rows) in every time I remove a row
This is the table code in HTML
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()" >
<br><br>
<table id="mytable" width="100%" border="2" >
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
and this is JavaScript code
var srn = 0;
function insert_row(){
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow(){
return document.getElementById("mytable").deleteRow(nb_of_rows);
}
}
function changeSR(){
return srn = srn + 1 ;
}
and this is an online share of my code
enter link description here
The issue occurs because the index in nb_of_rows is in danger of being out of date by the time the button is clicked (especially if other rows and have been added and deleted in the meantime). Therefore it will either delete the wrong row, or crash because the index doesn't exist in the table any more.
The solution is fairly simple: make the button get the parent row it belongs to, and then get that row's current index at the point of deletion, rather than relying on the index it had when it was added.
Usefully the row element has an index property telling you its current index in the table body, which makes this solution possible.
Here's the event code you need:
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement; //get the parent of the parent (i.e. the first parent is the table cell, and the parent of that is the row)
document.getElementById("mytable").deleteRow(row.rowIndex);
}
(BTW it makes no sense really to have a return statement in an event handler, since the control returns to somewhere in the JS event-handling engine, not to your code, so I removed that at the same time.)
Demo:
var srn = 0;
function insert_row() {
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement;
document.getElementById("mytable").deleteRow(row.rowIndex);
}
}
function changeSR() {
return srn = srn + 1;
}
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()">
<br><br>
<table id="mytable" width="100%" border="2">
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
I'm trying to assign an unique id to each row to then modify rows with specific number id's. However since the function is called every time on button click, I always get the same output for the number.
Here is my JavaScript Function
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var id =1;
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
</script>][1]
Here is my table declaration
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
and an image of my output just incase:
Basically you just need to move the id variable outside of the function. That way it's only set to 1 when your code loads, and then each function call increments it.
// global
var id = 1;
function insert_row() {
// ...
demo
// global
var id = 1;
function insert_row() {
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id = id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human + rowId.toString();
id++;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<input id="first_name" />
<input id="last_name" />
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
</div>
Since the id variable is being initialized in each function call, all the rows end up having the same id(that is, 1). One of the ways of solving this would be to simply place the var id = 1; declaration before the start of function insert_row() as a global variable.
However, in order to avoid using global variables, we could get the count of all the existing rows of the table and add 1 to it to get the new id in the following manner:
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// get count of the number of rows that already exist
var rowCount = table.getElementsByTagName("tr").length;
var id = rowCount + 1;
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(id);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
][1]
The HTML code would remain the same. In case your application is large or is headed towards being a large project, I'd strongly recommend using the second method instead of defining a global variable. Global variables tend to get very difficult to manage as the application size grows.
Please, make better code:
1) increase insertRow for each new line
2) don't repeat all document.getElementById for each call
3) don't mix html code with JS ( onclick="insert_row()" )
4) If you made a TABLE with THEAD, use TBODY
const
in_firstName = document.getElementById('first_name'),
in_lastName = document.getElementById('last_name'),
human_str = "human",
tableBody = document.querySelector('#saving_table tbody')
;
var Table_Row_ID = 0;
document.getElementById('insert-row').onclick = function()
{
// Create an empty <tr> element and add it to the 1st position of the table:
let row = tableBody.insertRow(Table_Row_ID);
row.id = ++Table_Row_ID;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
let
cell1 = row.insertCell(0),
cell2 = row.insertCell(1),
cell3 = row.insertCell(2)
;
// Add some text to the new cells:
cell1.textContent = in_firstName.value;
cell2.textContent = in_lastName.value;
cell3.textContent = human_str + row.id;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="container">
<input type="text" id="first_name" placeholder="first_name" />
<input type="text" id="last_name" placeholder="last_name" />
<button class="btn btn-primary" id="insert-row">Add Row</button>
</div>
Declare the counter outside of function.
Demo
Details commented in demo
// Reference tags
var btn = document.querySelector('button');
var first = document.getElementById('firstName');
var last = document.getElementById('lastName');
var spec = document.getElementById('species');
// Declare counter
var i = 0;
function insert_row(e) {
// Reference <tbody> (Not <table>)
var table = document.querySelector("tbody");
// Insert <tr> (No index is needed)
var row = table.insertRow();
// Add ID to <tr>
row.id = 'r' + i;
// for every loop...
for (let c = 0; c < 3; c++) {
// ...insert a <td>...
var cell = row.insertCell(c);
// ...1st loop add the value of first name input as text...
if (c === 0) {
cell.textContent = first.value;
// ...2nd loop add the value of last name input as text...
} else if (c === 1) {
cell.textContent = last.value;
// ...3rd loop add the value of species select as text...
} else if (c === 2) {
cell.textContent = spec.value;
// ...otherwise just end loop
} else {
break;
}
}
// Increment counter
i++;
}
// Add click event handler to button
btn.onclick = insert_row;
table {
table-layout: fixed;
width: 75%;
margin: 10px auto;
}
th {
width: 33%
}
td {
text-align: center
}
caption {
font-size: 1.2rem;
font-weight: 900;
}
input,
select,
button {
display: inline-block;
font: inherit;
height: 3ex;
line-height: 3ex;
vertical-align: middle;
}
select,
button {
height: 4ex;
}
button {
float: right
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Species</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input id='firstName' placeholder='First'>
<input id='lastName' placeholder='Last'>
<select id='species'>
<option value=''>Species</option>
<option value='Human 🕵'>Human 🕵</option>
<option value='Vampire 🧛'>Vampire 🧛</option>
</select>
<button class="btn btn-primary">Submit</button>
</div>
I'm trying to figure out how to add a new row to a table using Javascript but I also need to be able to add 3 columns into this table and here is where I am having problems. I can't seem to get it to work. Here is the javascript:
This adds rows with first field being ID entered into the first row but I don't know how to fill in columns.
function myCreateFunction() {
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++) {
var row = table.insertRow(2);
var cell1 = row.insertCell(0);
var div1 = document.createElement('div');
div1.innerHTML = "ID";
cell1.appendChild(div1);
div1.contentEditable = true;
}
}
Here is my Table:
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
try this
function myCreateFunction(thisObj) {
var buttonTr = thisObj.parentNode.parentNode;
var buttonTrHTML = buttonTr.outerHTML;
buttonTr.parentNode.removeChild(buttonTr);
var table = document.getElementById("myTable");
var add = 1;
for (var i = 0; i < add; i++)
{
table.innerHTML += "<tr><td>ID</td> <td>First Name</td><td>Last Name</td> <td>Add More</td><tr>";
}
//table.innerHTML += buttonTrHTML ;
table.appendChild(buttonTr );
}
and you need to pass the current Obj as
<button onclick="myCreateFunction(this)">Create row</button>
Try this
function myCreateFunction() {
var table = document.getElementById("myTable");
var rows = table.rows.length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = "ID";
cell1.contentEditable = true;
cell2.innerHTML = "First Name";
cell2.contentEditable = true;
cell3.innerHTML = "Last Name";
cell3.contentEditable = true;
var but1 = document.createElement('button');
but1.innerHTML = "Create row";
but1.setAttribute("onclick", "myCreateFunction()");
cell4.appendChild(but1);
var but2 = document.createElement('button');
but2.innerHTML = "Delete row";
but2.setAttribute("onclick", "myDeleteFunction()");
cell4.appendChild(but2);
}
<table id="myTable">
<tr>
<td>ID</td>
<td>First Name</td>
<td>Last Name</td>
<td>Add More</td>
</tr>
<tr>
<td>1</td>
<td>Jelly</td>
<td>Beans</td>
<td><button onclick="myCreateFunction()">Create row</button><button onclick="myDeleteFunction()">Delete row</button></td>
</tr>
</table>
I solved this a bit different. And it works fine (also with deleting rows):
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var maxRows = 10;
if (rowCount < maxRows) {
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
} else {
alert("Max. Tabs= " + maxRows);
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (chkbox != null && chkbox.checked == true) {
if (rowCount <= 1) {
alert("Min Tabs = 1");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Try following function
function myCreateFunction() {
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
console.log(rowCount)
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = rowCount;
cell2.innerHTML = ""; //put your text/html here
cell2.innerHTML = ""; //put your text/html here
}
put your desired text or html in innerHTML of the respected cell
Also for Pavel's answer your markup is wrong(though I haven't tested the function). The table id 'myTable' should be passed as string.
<button onclick="addRow('myTable')">Create row</button>
could not comment for not having enough reputation
Hope this helps.
So I have a table with one row and two columns that creates new rows with info input by the user.
I want to know how to add info into the second column of cells.
The following code adds cells to the first column only:
<!DOCTYPE HTML>
<html>
<body>
Something must be entered here:
<input id="inputName" style="width:100px;"></input>
<button onclick="addRowCell('table1')">Add row</button>
<table id="table1" style="border:1px solid black;">
<tr id="myRow1">
<td>ID</td>
<td>Content 1</td>
</tr>
</table>
<script>
i=1;
function addRowCell(el){
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
x.innerHTML=fName;
i++;
}
</script>
</body>
</html>
JSFiddle for the above: http://jsfiddle.net/tC2zG/
Edit: for anyone with a similar problem - what you see here isn't cells being added, it's rows being added.
You're not adding cells at all, just rows, so add a couple of cells
i = 1;
function addRowCell(el) {
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
var c1 = x.insertCell(0);
var c2 = x.insertCell(1);
c2.innerHTML = fName;
i++;
}
FIDDLE
Update on your JS Fiddle:
i=1;
function addRowCell(el){
var table = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "ID";
cell2.innerHTML = fName;
i++;
}
Please check if that is the result that you were hoping for.
I am writing a code in HTML + Jquery and need to add rows to a table dynamically.
I've written the code to add the rows dynamically, but it doesn't seem to work.
Here is my JScript code :
<script language="JavaScript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "date";
element1.name="datebox[];
element1.id = "dt";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var element2 = document.createElement("input");
element2.type = "select";
element2.name = "selectbox[]";
element2.id = "slct";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount + 1;
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
element3.id = "txt";
cell3.appendChild(element3);
table.appendChild(cell1);
}
</script>
This is my Table:
<table id = "tab" style="width:500px">
<tr>
<th>Date</th>
<th>Treatment Goal</th>
<th>Comment</th>
</tr>
<tr>
<td><INPUT type="date" name="datebox[]" id = "dt"/></td>
<td>
<SELECT name="selectbox[]" id = "slct">
</SELECT>
</td>
<td><INPUT type="text" name="txtbox[]" id = "txt"/></td>
</tr>
</table>
I am calling the function in the onClick event of a button like this :
<input type="button" id="add" value="+" name="Add" onclick="addRow('tab')"/>
The html page doesn't respond to the click event and nothing happens.
Cannot understand what's going wrong.
Working Fiddle
The first problem is a syntax error on this line (you didn't close the double quote):
element1.name="datebox[];
^ missing "
The second problem is you are appending the cell to the table which is wrong, you should be appending the row:
table.appendChild(row);
^ changed to row from cell
You are missing a quotation mark on the line:
element1.name="datebox[];
after the name element.