Adding a row on top-1 position in html table - javascript

function addRowtoTop(first) {
// get input values
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var city = document.getElementById('city').value;
var country = document.getElementById('country').value;
// get the html table
// 0 = the first table
var table = document.getElementsByTagName('table')[0];
// add new empty row to the table
// 0 = in the top
// table.rows.length = the end
// table.rows.length/2+1 = the center
var newRow = table.insertRow((table.rows.length / 0));'
i have been trying to add a row on top-1 position on a html table but cant figure out how. by this line var newRow = table.insertRow((table.rows.length / 0)); i am able to add the row on top but it gets added above the heading part. Thanks in advance

you need to store the head in a variable, then the new row and then take the rest of the rows,
at the end, just table.innerHTML = newTable;
function addRow(){
var table = document.querySelector('table');
var Head = table.children[0].children[0].outerHTML;
var newRow = '<tr><td>newShoes</td><td>Shoes</td><td>Shoes</td></tr>';
var restOfTheTable = '';
for(var i = 1; i<=table.children[0].children.length-1; i++){
restOfTheTable += (table.children[0].children[i].outerHTML);
}
table.innerHTML = `${Head}${newRow}${restOfTheTable}`;
}
<table>
<tr>
<td>name</td>
<td>Price</td>
<td>Location</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
<tr>
<td>Shoes</td>
<td>Shoes</td>
<td>Shoes</td>
</tr>
</table>
<button onclick="addRow()">add row</button>

Related

How can I break row from specific <td> to next row?

I need to break table headings well as table rows after 4 . Here I'm generating table dynamically from JSON string through jQuery. The table can contain maximum 16 columns, so I need to break it in 4 rows. The output should look like,
<table border=1>
<thead>
<tr>
<th>COLUMN1</th>
<th>COLUMN2</th>
<th>COLUMN3</th>
<th>COLUMN4</th>
</tr>
<tr>
<td>val1</td>
<td>val2</td>
<td>val3</td>
<td>val4</td>
</tr>
</thead>
<tbody>
<tr>
<th>COLUMN5</th>
<th>COLUMN6</th>
<th>COLUMN7</th>
<th>COLUMN8</th>
</tr>
<tr>
<td>val5</td>
<td>val6</td>
<td>val7</td>
<td>val8</td>
</tr>
</tbody>
</table>
I'm using below code to generate HTML Table from JSON,
var txnJson = JSON.parse('<%=jsonObj1%>');
var tableName;
var colspan = 0;
var colHeader = [];
var rowValue = [];
for (var key in txnJson) {
tableName = key;
console.log(key);
for (var secondKey in txnJson[key]) {
console.log(secondKey + ' : ' + txnJson[key][secondKey]);
for (var thirdkey in txnJson[key][secondKey]) {
colHeader.push(thirdkey);
rowValue.push(txnJson[key][secondKey][thirdkey]);
colspan = colspan +1;
console.log(thirdkey + ' : ' + txnJson[key][secondKey][thirdkey]);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < colHeader.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.setAttribute("class", "RptHeader");
th.innerHTML = colHeader[i];
tr.appendChild(th);
}
tr = table.insertRow(-1);
for (var j = 0; j < rowValue.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = rowValue[j];
}
$('#Div<%=i%>').append(table);
I have tried using $('').html($('#Test1 td:gt(4)')).appendTo('#Test1'); but it only breaks single row. I need to iterate it after every four td.
How can I do it?
I'm able to achieve the same using below code,
`var inp = document.createElement("input");
inp.setAttribute("type","hidden");
inp.setAttribute("id","colCnt<%=i%>");
inp.setAttribute("value",colLength);
$(function () {
var colCnt = $("#colCnt<%=i%>").val();
var thLen = 3;
var tdLen = 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+thLen+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+tdLen+')')).appendTo('#Tab<%=i%>');
for (var k = 0; k < colCnt; k++) {
thLen = thLen + 4;
tdLen = tdLen + 4;
$('<tr>').html($('#Tab<%=i%> th:gt('+(thLen)+')')).appendTo('#Tab<%=i%>');
$('<tr>').html($('#Tab<%=i%> td:gt('+(tdLen)+')')).appendTo('#Tab<%=i%>');
}
});
Hope, this might help someone.

Adding new row to table with three columns Javascript html click function

Desrciption
I'd like to able to add a row using javascript with three columns to a table in html.
I am creating a table where the user can enter their own text and add the text along with two other pieces of information to the table into three columns. The current code that I have will not display the new row. The code also includes a drag and drop feature where the user can click on the row and drag it into a different position into the table.
I am asking for guidance as to why when I press the click button it does not add a new row to the table.
edit: Code is now working after update, but the else statement does not do anything.
Javascript
function addRow(mytable) {
var food = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode(document.querySelector('.input2').value);
var time = document.createTextNode(document.querySelector('.input3').value);
document.querySelector('.input').value = '';
document.querySelector('.input2').value = '';
document.querySelector('.input3').value = '';
// Get a reference to the table
if (food !== '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = food;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
//not working for some reason
else {
document.getElementById("msg").innerHTML = "Please enter a name";
}
}
javascript click
document.getElementById('btn').addEventListener('click', function( {addRow('mytable');});
HTML
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<div id="addRow"></div>
</table>
Few adjustments below, but more detail needed, atm only one text input for component, but can add more for cook/time
function addRow(mytable) {
var newItem = document.createTextNode(document.querySelector('.input').value);
var category = document.createTextNode("Cook");
var time = document.createTextNode("time");
document.querySelector('.input').value = '';
// Get a reference to the table
if (newItem != '') {
var tableRef = document.getElementById(mytable);
var attr = document.createAttribute('draggable');
attr.value = 'true';
// Insert a row at the end of the table
var newRow = tableRef.insertRow(-1);
newRow.setAttributeNode(attr);
newRow.className = 'draggable';
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newCell3 = newRow.insertCell(2);
var newText = newItem;
var newText2 = category;
var newText3 = time;
newCell.appendChild(newText);
newCell2.appendChild(newText2);
newCell3.appendChild(newText3);
addEventsDragAndDrop(newRow);
}
}
document.getElementById('btn').addEventListener('click', function(){addRow('mytable');});
<table id="mytable">
<tr>
<th>Component</th>
<th>Category</th>
<th>Time</th>
</tr>
<tr class="draggable" id="draggable" draggable="true">
<td>Food goes here</td>
<td>Cook</td>
<td>10</td>
</tr>
<div id="addRow"></div>
</table>
<label for='component'>component</label>
<input class='input' id='component' />
<button id='btn'>add component</button>

Delete table rows having selected id using javascript

I am trying to make the code to add and remove desired rows on selecting id in the select box. My code is below :
HTML code :
<body>
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select><br/><br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>
</body>
My javascript code :
<script type="text/javascript">
var employees=new Array(2);
for(i=0;i<2;i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include(){
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
</script>
Add button works fine. but for remove button I cant get a function to remove all the rows with selected id. Can anyone suggest me?
My code in jsfiddle : https://jsfiddle.net/noona/fNPvf/23235/
use querySelectorAll and rowIndex to achieve this. here is your updated code
var employees = new Array(2);
for (i = 0; i < 2; i++)
employees[i] = new Array(3);
employees[0][0] = 1;
employees[0][1] = "Rahul";
employees[0][2] = "Administer";
employees[1][0] = 2;
employees[1][1] = "Raj";
employees[1][2] = "Manager";
function include() {
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
id = id - 1;
row.id = id;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var id = document.getElementById("select_id").value - 1;
var table = document.getElementById("table");
rowsCount = table.querySelectorAll('tr[id="' + id + '"');
for (var i = 0; i < rowsCount.length; i++) {
table.deleteRow(rowsCount[i].rowIndex);
}
}
<table id="table" border="1" style="float:left">
<tr>
<td>Employee id</td>
<td>Name</td>
<td>Designation</td>
</tr>
</table>
<select id="select_id" style="float:right">
<option>--select--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<br/>
<br/>
<button onclick="delete_row()" style="float:right">remove</button>
<button onclick="include()" style="float:right">add</button>
When adding a new row, give the newly added rows an attribute that holds it's id value. Then you can delete all the rows whose attribute value is equal to selected id in dropmenu.
you can try below:
function include(){
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
var table = document.getElementById("table");
var row = table.insertRow();
// give the new row an attribute that can identify itself
row.setAttribute("emplId",id);
id=id-1;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);
col1.innerHTML = employees[id][0];
col2.innerHTML = employees[id][1];
col3.innerHTML = employees[id][2];
}
function delete_row() {
var table = document.getElementById("table");
var id = document.getElementById("select_id").value;
for(var i = 0; i<table.rows.length; i++) { // iterate through the rows
var rowEmplId = table.rows[i].getAttribute("emplId");
if(rowEmplId==id) { // found a row matches the selected option
table.deleteRow(i); // remove this row
i--; // we just removed a row, so we need to adjust the cursor
}
}
}

Appending tr to table appends a new tbody to html table using javascript

Please check this fiddle: http://jsfiddle.net/tn4euhsn/8/
HTML:
<table id="tab" border=1>
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</table>
Javascript:
console.log("Here!");
var table = document.getElementById("tab");
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
var td1 = document.createElement("td");
td1.innerHTML= "r2col1";
var td2 = document.createElement("td");
td2.innerHTML= "r2col2";
trnew.appendChild(td1);
trnew.appendChild(td2);
table.appendChild(trnew);
console.log(table.outerHTML);
I am trying to append a new <tr> to a table. But instead a <tbody><tr></tr></tbody>
gets appended, resulting in 2 <tbody> elements in html table.
So whats wrong here? and how do I do it? (I don't want to use jquery)
Yes it already has a default tbody tag so you have to use it instead of introducing new one.
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
Also you can simplify it like
var table = document.getElementById("tab").getElementsByTagName('tbody')[0];
var trnew = document.createElement("tr");
trnew.id = "row" + 2;
for (var i=1; i<=2; i++) {
var td = document.createElement("td");
td.innerHTML = "r2col" + i;
trnew.appendChild(td);
}
table.appendChild(trnew);
console.log(table.outerHTML);
Update:
While trying to figure out the reason, I came across HTMLTableElement,
If a table has multiple tbody elements, by default, the new row is
inserted into the last tbody. To insert the row into a specific tbody
Here is an updated version of the above code
var table = document.getElementById("tab");
var index = table.getElementsByTagName("tr").length;
var newRow = table.insertRow(index);
newRow.id = "row" + 2;
for (var i = 0; i < 2; i++) {
var newCell = newRow.insertCell(i);
var newText = document.createTextNode("r2col" + i);
newCell.appendChild(newText);
}
console.log(table);
Fiddle
It seems that the browser will give it a tbody by default, try this:
<table border=1>
<tbody id="tab">
<tr>
<td>A col1</td>
<td>A col2</td>
</tr>
</tbody>
</table>
Append to the tbody not to the table.
Updated Fiddle

How do I get data from a table?

How do I pull data (string) from a column called "Limit" in a table ("displayTable") in Javascript?
var table = document.getElementById('displayTable');
var rowCount = table.rows.length;
for (var i = 1; i < rowCount - 1; i++) {
var row = table.rows[i]["Limit"].ToString();
alert(row);
...
}
This is how I accomplished reading a table in javascript. Basically I drilled down into the rows and then I was able to drill down into the individual cells for each row.
This should give you an idea
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
/* get your cell info here */
/* var cellVal = oCells.item(j).innerHTML; */
}
}
UPDATED SCRIPT
//gets table
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++){
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//loops through each cell in current row
for(var j = 0; j < cellLength; j++){
// get your cell info here
var cellVal = oCells.item(j).innerHTML;
console.log(cellVal);
}
}
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
In this code data is a two dimensional array of table data
let oTable = document.getElementById('myTable');
let data = [...oTable.rows].map(t => [...t.children].map(u => u.innerText))
console.log(data);
<table id="myTable">
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
</table>
use Json & jQuery. It's way easier than oldschool javascript
function savedata1() {
var obj = $('#myTable tbody tr').map(function() {
var $row = $(this);
var t1 = $row.find(':nth-child(1)').text();
var t2 = $row.find(':nth-child(2)').text();
var t3 = $row.find(':nth-child(3)').text();
return {
td_1: $row.find(':nth-child(1)').text(),
td_2: $row.find(':nth-child(2)').text(),
td_3: $row.find(':nth-child(3)').text()
};
}).get();

Categories

Resources