I have a function to generate rows from Javascript, and a function to clear it, but when delete I can't use the function to create again because it removes all.
I need to remove only the content and don't find how.
function myFunction() {
var stock = new Array()
stock[0] = new Array("Cars", "1", "2", "3", "4", "5")
stock[1] = new Array("Veggies", "11", "22", "33", "44", "55")
stock[2] = new Array("Colors", "111", "222", "333", "444", "555")
stock[3] = new Array("Numbers", "1111", "2222", "3333", "4444", "55555")
stock[4] = new Array("Requests", "28.625", "68.625", "22", "22", "22")
var table = document.getElementById("tableBody");
for (i = 0; i < stock.length; i++) {
var row = table.insertRow(i);
for (j = 0; j < stock[i].length; j++) {
var cell = row.insertCell(j);
cell.innerHTML = stock[i][j];
}
}
}
function removeTable(id) {
var tbl = document.getElementById(id);
if (tbl) tbl.parentElement.removeChild(tbl);
}
table,
td {
border: 1px solid black;
}
<table id="tablaPass" width="100%" height="20" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr height="40px">
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Marca</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Modelo</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Version</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Puertas</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">Potencia</th>
<th style="padding: 10px;" background="<html:rewrite page='/images/layout/capcelera2.gif' />" valign="middle" class="TituloPestana">F. Lanzamiento</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<br>
<button onclick="myFunction()">Try it</button>
<input type="button" onclick="removeTable('tableBody');" value="Remove!" />
Clear just the rows:
var tbody = document.getElementById('tableBody');
var rows = tbody.querySelectorAll('tr');
for (i = 0; i < rows.length; i++)
tbody.removeChild(rows[i]);
function myFunction() {
var stock = []
stock[0] = ["Cars", "1", "2", "3", "4", "5"]
stock[1] = ["Veggies", "11", "22", "33", "44", "55"]
stock[2] = ["Colors", "111", "222", "333", "444", "555"]
stock[3] = ["Numbers", "1111", "2222", "3333", "4444", "55555"]
stock[4] = ["Requests", "28.625", "68.625", "22", "22", "22"]
var table = document.getElementById("tableBody");
for (i = 0; i < stock.length; i++) {
var row = table.insertRow(i);
for (j = 0; j < stock[i].length; j++) {
var cell = row.insertCell(j);
cell.innerHTML = stock[i][j];
}
}
}
function removeTable(id) {
// Get the table body
var tbody = document.getElementById(id);
// Find and remove all the <tr> in the body
var rows = tbody.querySelectorAll('tr');
for (i = 0; i < rows.length; i++)
tbody.removeChild(rows[i]);
}
document.getElementById('tryit').addEventListener('click', myFunction);
document.getElementById('removeit').addEventListener('click', function() {
removeTable('tableBody');
});
table,
td {
border: 1px solid black;
}
th {
padding: 10px;
}
<table id="tablaPass" width="100%" height="20" border="0" cellspacing="0" cellpadding="0">
<thead>
<tr height="40px">
<th valign="middle">Marca</th>
<th valign="middle">Modelo</th>
<th valign="middle">Version</th>
<th valign="middle">Puertas</th>
<th valign="middle">Potencia</th>
<th valign="middle">F. Lanzamiento</th>
</tr>
</thead>
<tbody id="tableBody">
</tbody>
</table>
<br>
<button id="tryit">Try it</button>
<button id="removeit">Remove</button>
Check this out, this is another way to do it
function removeTable(id)
{
var tbl = document.getElementById(id);
tbl.innerHTML = ''
}
Related
How can I get email cell value when I click on the button which is located at the last cell of the same row.
Please check this screenshot for better understanding what I mean
So when I click Button 1, I want to get Email1 value or when click Button 2, I want to get N2 cell value.
My HTML Mockup:
function renderCustomers(tasks) {
customerList.innerHTML += `
<tr >
<th >Name</th>
<th >Email</th>
<th >Contacts</th>
<th >Address</th>
<th >Country</th>
<th >Action</th>
</tr>`;
tasks.forEach((t) => {
customerList.innerHTML += `
<tr class=" animated bounceInUp">
<td >${t.Name}</td>
<td >${t.Email}</td>
<td >${t.Contacts}</td>
<td >${t.Address}</td>
<td >${t.Country}</td>
<td ><button class="btn btn-success btn-xs" id="getCustomerEmail">
Get Customer Email
</button></td>
</tr>`;
});
}
I found this function but it return the clicked cell value not the one I need:
function getElementID(){
var tbl = document.getElementById("Results");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
}
Any help is really appreciated
I found this function but it return the clicked cell value not the one I need:
function getElementID(){
var tbl = document.getElementById("MyTable");
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () { getval(this); };
}
}
function getval(cel) {
alert(cel.innerHTML);
}
}
I think you simply bind a class to your td and then reference it based on the context of the clicked button.
function getEmail(el) {
const tr = el.closest('tr');
const tds = tr.getElementsByClassName('email');
console.log(tds[0].innerHTML);
}
<table>
<thead>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</thead>
<tbody>
<tr>
<td>Salvino</td>
<td class="email">salvino#example.com</td>
<td><button onclick="getEmail(this)">Button</button></td>
</tr>
<tr>
<td>Someone</td>
<td class="email">someone#example.com</td>
<td><button onclick="getEmail(this)">Button</button></td>
</tr>
</tbody>
</table>
I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);
I would like to Beautify the html code which I get from database.
Which is the best method to do this without using libraries.
I get this information from DB:
#{ var model = (Text.Alert.Models.AlertTemplateModel)Model; var contentItems = model.ContentItems.OrderByDescending(d => d.PublicationDate).ToArray(); } #for (int i = 0; i < contentItems.Count(); i++){ <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody> <tr valign="top"> #if (!String.IsNullOrEmpty(contentItems[i].MediaUrl)) { <td width="132"><img src="#(contentItems[i].MediaUrl)" style="display: block;" alt="" width="103"> </td> } <td> <font color="#7391a2" size="2"> <font color="#d1065a" size="3"> #if (!string.IsNullOrEmpty(contentItems[i].Url)) { #(contentItems[i].Title) } else { #(contentItems[i].Title) } </font> <br> #(Raw(contentItems[i].Description)) </font> </td> </tr> </tbody> </table> <br/> }";
This is my function:
function makeReadable(text) {
var readableHTML = text;
var lb = '\r\n';
//var htags = ["var", "#{", "#for", "#if", "#else", "}", "<img", "<html", "</html>", "</head>", "<title", "</title>", "<meta", "<link", "<style", "</style>", "</body>"];
var htags = ["var","#{","#for","#if","#else","}","<img", "<"];
for (i = 0; i < htags.length; ++i) {
var hhh = htags[i];
readableHTML = readableHTML.replace(new RegExp(hhh, 'gi'), lb + hhh);
}
var btags = ["</div>", "</span>", "</form>", "<a", "<font", "</fieldset>", "<br>", "<br />", "</a>", "<hr", "<pre", "</pre>", "<blockquote", "</blockquote>", "<ul", "</ul>", "<ol", "</ol>", "<li", "<dl", "</dl>", "<dt", "</dt>", "<dd", "</dd>", "<\!--", "<table", "</table>", "<caption", "</caption>", "<th", "</th>", "<tr", "</tr>", "<td", "</td>", "<script", "</script>", "<noscript", "</noscript>"];
for (i = 0; i < btags.length; ++i) {
var bbb = btags[i];
readableHTML = readableHTML.replace(new RegExp(bbb, 'gi'), lb + bbb);
}
var ftags = ["<label", "</label>", "<legend", "</legend>", "<object", "</object>", "<embed", "</embed>", "<select", "</select>", "<option", "<option", "<input", "<textarea", "</textarea>"];
for (i = 0; i < ftags.length; ++i) {
var fff = ftags[i];
readableHTML = readableHTML.replace(new RegExp(fff, 'gi'), lb + fff);
}
var xtags = ["<body", "<head", "<div", "<span", "<p", "<form", "<fieldset"];
for (i = 0; i < xtags.length; ++i) {
var xxx = xtags[i];
readableHTML = readableHTML.replace(new RegExp(xxx, 'gi'), lb + lb + xxx);
}
return readableHTML;
}
When I Use my Function the result is this:
#{ var model = (Text.Alert.Models.AlertTemplateModel)Model; var contentItems = model.ContentItems.OrderByDescending(d => d.PublicationDate).ToArray(); } #for (int i = 0; i < contentItems.Count(); i++) {
<table border="0" cellpadding="0" cellspacing="0" width="100%"> <tbody>
<tr valign="top"> #if (!String.IsNullOrEmpty(contentItems[i].MediaUrl)) {
<td width="132"><img src="#(contentItems[i].MediaUrl)" style="display: block;" alt="" width="103">
</td> }
<td>
<font color="#7391a2" size="2">
<font color="#d1065a" size="3"> #if (!string.IsNullOrEmpty(contentItems[i].Url)) {
<a href="#(contentItems[i].Url)">#(contentItems[i].Title)
</a> } else { #(contentItems[i].Title) } </font>
<br> #(Raw(contentItems[i].Description)) </font>
</td>
</tr> </tbody>
</table> <br/> }
";
I have the following code to create a left and right border when a row is selected in a table. I want the borders to only appear when the row is currently selected, and to disappear when it is not selected.
I attach a mock up:
function addRowHandlers() {
var table = document.getElementById("example");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
row.getElementsByTagName("td")[0].style.backgroundColor = "white";
row.firstElementChild.style.borderLeft = "black solid 2px";
row.lastElementChild.style.borderRight = "black solid 2px";
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
tr td:first-child { border-left:2px solid transparent;}
tr td:last-child { border-right:2px solid transparent;}
<div>
<table id="example">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
Use a class for the current selection styles ( I named it highlight) then on click remove this class from all rows with this
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].classList.remove('highlight');
}
and then add it to the current row with row.className += "highlight"; check it out:
function addRowHandlers() {
var table = document.getElementById("example");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row) {
return function() {
for (var i = 0; i < table.rows.length; i++) {
table.rows[i].classList.remove('highlight');
}
var cell = row.getElementsByTagName("td")[0];
row.getElementsByTagName("td")[0].style.backgroundColor = "white";
row.className += "highlight";
var id = cell.innerHTML;
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
tr:not(.highlight) td:first-child { border-left:2px solid transparent;}
tr:not(.highlight) td:last-child { border-right:2px solid transparent;}
tr.highlight td:first-child { border-left:2px solid black;}
tr.highlight td:last-child { border-right:2px solid black;}
<div>
<table id="example">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
Here I tried a differenct approach with less code.
If you inspect from console, you'll see the change: click event adds the class to that row, and resets other rows' classes.
var mytable = document.getElementById("example");
var myrows = mytable.rows;
function giveStyle(el) {
Array.from(myrows).map(e => e.className = "");
el.className = "someclass";
}
.someclass {
/*something here */
}
<table id="example">
<tr>
<td>First</td>
<td>Last</td>
<td>Age</td>
</tr>
<tr onclick="giveStyle(this)">
<td>John</td>
<td>Doe</td>
<td>50</td>
</tr>
<tr onclick="giveStyle(this)">
<td>Alice</td>
<td>Wilsom</td>
<td>40</td>
</tr>
<tr onclick="giveStyle(this)">
<td>Otto</td>
<td>Weininger</td>
<td>25</td>
</tr>
</table>
Please use this function also :
function resetRowHandlers() {
var table = document.getElementById("example");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var row = table.rows[i];
row.getElementsByTagName("td")[0].style.backgroundColor = "none";
row.firstElementChild.style.borderLeft = "transparent solid 2px";
row.lastElementChild.style.borderRight = "transparent solid 2px";
}
}
Also call this function on click of row i.e. createClickHandler
I need to loop through .mainheader class to .mainheader because i need header class row and values class row value for grouping
This is my html
<table id="t01" cellspacing="0" cellpadding="0" class="table" style="margin-top:20px">
<thead>
<tr>
<th class="sorting">Group_Main_ID</th>
<th class="sorting">Group_Sub_ID</th>
<th class="sorting">Item</th>
<th class="sorting">Instructions</th>
<th class="sorting">Decision_Request_Input</th>
<th class="sorting">Status</th>
<th class="sorting">Evidence_Info</th>
<th class="sorting">Evidence_Doc</th>
</tr>
</thead>
<tfoot></tfoot>
<tbody id="editContents">
<tr id="1" class="mainheader " bgcolor="#000033">
<td id="nonEdit" class="th1 p_no" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header1</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
SubHeader1</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header1.2</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
<tr id="1" class="mainheader " bgcolor="#000033">
<td id="nonEdit" class="th1 p_no" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
Header2</td>
</tr>
<tr id="2" class="header " bgcolor="#000033" style="opacity:0.8">
<td id="nonEdit" class="th1" bgcolor="#215F8B">
<font color="white" align="left"></font>
</td>
<td class="th" bgcolor="#215F8B" align="left" style="color: white; display: table-cell;" colspan="7">
<font color="white" align="left"></font>
SubHeader2.1</td>
</tr>
<tr class="values">
<td class="sno">1</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>null</td>
<td>Yes#No#NA</td>
</tr>
</tbody>
</table>
My Javascript
var groupData = {};
var subGroupData = {};
var arr = [];
$('#t01 tbody tr.mainheader').each(function(i) {
var groupIdData ={};
groupIdData['id'] = $(this).attr('id');
groupIdData['name'] = $(this).find('td:eq(2)').text().trim()
groupIdData["action"]= 'Add/Edit/Delete'
//arr.push(garr)
groupData['group'] = groupIdData;
groupData['subgrps'] = [];
subGroupData = {};
subGroupData["action"]= 'Add/Edit/Delete'
subGroupData['id'] =$(this).next('.header').attr('id');
subGroupData['name']= $(this).next('.header').find('td:eq(2)').text().trim();
//arr.push(garr)
groupData['subgrps'].push(subGroupData)
subGroupData['items'] = [];
var items = [];
$(this).next('tr').each(function(){
if($(this).hasClass('values'))
{
var rowData = {};
$(this).find('td').each(function(i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
if(i == 0)
rowData["Action"]='Add/Edit/Delete'
if(i>1)
rowData[thh]=$(this).text().trim()
});
//arr.push(garr)
items.push(rowData)
}
else
return
});
//console.log('over')
}
subGroupData['items'].push(items);
groupData['subgrps'].push(subGroupData);
arr.push(groupData);
});
alert(JSON.stringify(arr)) ;
My Fiddle
https://jsfiddle.net/694kjj3o/
I am expecting JSON look like this
[
{
"group": {
"value": "Header1"
},
"subgrps": [
{
"name": {
"value": "SubHeader1.1"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
],
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
},
{
"name": {
"value": "SubHeader1.2"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
}
]
},
{
"group": {
"value": "Header2"
},
"subgrps": [
{
"name": {
"value": "Header2.1"
},
"items": [
[
{
"value": {
"Group_Main_ID": 1,
"Group_Sub_ID": 5,
"Item": "4",
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
}
]
]
}
]
}
]
I am unable loop it . Kindly guide me in this situation
Try
var arr = [];
$('#t01 tbody tr.mainheader').each(function (i) {
var $main = $(this),
main = {
"group": {
"value": $main.text().trim()
},
"subgrps": []
};
console.group($main.text().trim());
console.log(this);
$main.nextUntil('.mainheader', '.header').each(function () {
var $header = $(this),
header = {
"name": {
"value": $header.text().trim()
},
"items": []
};
console.group($header.text().trim());
console.log(this);
$header.nextUntil('.mainheader, .header', '.values').each(function (i) {
var $tr = $(this),
$tds = $tr.children(),
obj = {
"value": {
"Group_Main_ID": $tds.eq(0).text().trim(),
"Group_Sub_ID": $tds.eq(1).text().trim(),
"Item": $tds.eq(2).text().trim(),
"Instructions": null,
"Decision_Request_Input": null,
"Status": null,
"Evidence_Info": null,
"Evidence_Doc": null
}
};
console.group(i);
console.log(this);
header.items.push(obj);
console.groupEnd();
});
main.subgrps.push(header);
console.groupEnd();
});
arr.push(main);
console.groupEnd();
});
console.log(arr)
console.log(JSON.stringify(arr));
Demo: Fiddle
If you want to get dynamic key and values
var arr = [];
$('#t01 tbody tr.mainheader').each(function (i) {
var $main = $(this),
main = {
"group": {
"action":'Add/Edit/Delete',
"value": $main.text().trim()
},
"subgrps": []
};
//console.group($main.text().trim());
//console.log(this);
$main.nextUntil('.mainheader', '.header').each(function () {
var $header = $(this);
header = {
"name": {
"action":'Add/Edit/Delete',
"value": $header.text().trim()
},
"items": []
};
//console.group($header.text().trim());
//console.log(this);
$header.nextUntil('.mainheader, .header', '.values').each(function (i) {
var $tr = $(this);
obj = {};
obj.action = 'Add/Edit/Delete';
var sobj = {}
$tr.find('td').each(function (i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
sobj[thh] = $(this).text().trim()
});
obj.value = sobj;
//console.group(i);
//console.log(this);
header.items.push(obj);
//console.groupEnd();
});
main.subgrps.push(header);
//console.groupEnd();
});
arr.push(main);
//console.groupEnd();
});
//console.log(arr)
console.log(JSON.stringify(arr));
DEMO
https://jsfiddle.net/95nqr6op/6/
Your code is having extra closing curly bracket }.
I Updated the code. There are some errors I found on the console.
$('#t01 tbody tr.mainheader').each(function(i) {
var groupIdData = {};
groupIdData['id'] = $(this).attr('id');
groupIdData['name'] = $(this).find('td:eq(2)').text().trim()
groupIdData["action"] = 'Add/Edit/Delete'
//arr.push(garr)
groupData['group'] = groupIdData;
groupData['subgrps'] = [];
subGroupData = {};
subGroupData["action"] = 'Add/Edit/Delete'
subGroupData['id'] = $(this).next('.header').attr('id');
subGroupData['name'] = $(this).next('.header').find('td:eq(2)').text().trim();
//arr.push(garr)
groupData['subgrps'].push(subGroupData)
subGroupData['items'] = [];
var items = [];
$(this).next('tr').each(function() {
if ($(this).hasClass('values')) {
var rowData = {};
$(this).find('td').each(function(i) {
var thh = $(this).closest('table').find('th').eq($(this).index()).text();
if (i == 0)
rowData["Action"] = 'Add/Edit/Delete'
if (i > 1)
rowData[thh] = $(this).text().trim()
});
//arr.push(garr)
items.push(rowData)
} else
return
});
//console.log('over')
subGroupData['items'].push(items);
groupData['subgrps'].push(subGroupData);
arr.push(groupData);
});