inserting td in a tr with ID using javascript - javascript

I have to insert a td inside a tr which has a ID using javascript.Can someone please help me or guide me in the right direction.Sorry it might be simple but I m very new to javascript.
<html>
<head>
<script type="text/javascript">
function insertText ()
{
//function to insert any text on the tr with id "tr1"
}
</script>
</head>
<body onload="javascript:insertText()">
<table>
<tr id="tr1">
</tr>`
</table>
</body>
</html>

function insertText ()
{
var td = document.getElementById('tr1').insertCell(0);
td.innerHTML = "Some Text";
}
The main advantage of insertCell (and insertRow) is that they allow you to specify an index where the new cell (or row) is to be inserted.

Try this:
function insertText ()
{
var el = document.createElement('td');
el.innerHTML = 'Hello World';
document.getElementById("tr1").appendChild(el);
}

Related

Save dynamically created table content in excel file using SheetJS

I add rows into html table dynamically and I want to save the table content into xlsx file using SheetJs. The generated file is empty. Is somehow possible to do this in this case when table content was added this way?
I also tried to add the rows rigth before creating the xlsx file..
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"
integrity="sha256-siFczlgw4jULnUICcdm9gjQPZkw/YPDqhQ9+nAOScE4=" crossorigin="anonymous"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
<style>
table,
td {
border: 1px solid black;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.10.3/xlsx.full.min.js">
</script>
<p>Click the button to add a new row at the first position of the
table and then add cells and content</p>
<table id="myTable">
<TR>
</TR>
</table>
<button type="button" id="first" onclick="First('myTable')">Principal</button>
<button id="button-a">Create Excel</button>
<script>
function First(tableID) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>first</tr>";
}
</script>
<script>
var wb = XLSX.utils.table_to_book(document.getElementById('myTable'), { sheet: "Sheet JS" });
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' });
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
$("#button-a").click(function () {
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), 'test.xlsx');
});
</script>
</body>
</html>
Issues
text inside tr instead of td in dynamic content. This results in the table structure like below.
XLSX.utils.table_to_book called before table content created.
Working Demo
https://jsfiddle.net/aswinkumar863/95zsfg64/1/

Creating unique Id buttons in a javascript loop

I need to create a table populated with buttons. Each button must have a unique id in order to edit values in it's row. I set an alert displaying button's id on click, but all created buttons seem to have the same ID. What's wrong with my code?
plz help, im really newbie in js. Any help will be highly appreciated.
this is my code:
<!doctype html>
<html>
<head>
<title>js table</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<table id="TableA" dir="ltr" width="500" border="1">
<tr>
<td>Old top row</td>
</tr>
</table>
</body>
<script type="text/javascript" >
for (var i = 0; i<6; i++) {
// Get a reference to the table
var tableRef = document.getElementById("TableA");
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var boton = newRow.insertCell(0);
// Append a text node to the cell
var newButton = document.createElement("BUTTON");
newButton.id = i;
newButton.innerHTML = "Unique id button";
boton.appendChild(newButton);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createElement("P");
newText.innerHTML = "item" +" "+ i;
newCell.appendChild(newText);
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
}
</script>
Change your client handler to refer to the actual button that was clicked. Change from this:
newButton.onclick = function(){
alert("Button Id: " + newButton.id);
}
to this:
newButton.addEventListener("click", function(e) {
alert("Button Id: " + this.id);
});
The variable newButton is used over and over again in your for loop so by the time any of your onclick handlers actually run, all the buttons have been created and newButton will contain the last value it ever had.
Instead, you can use this to refer to the element that was clicked on so this.id will the id value of the button that was clicked.
Note: I also switch to using .addEventListener() which also passes an event data structure to the event handler (shown as the e argument in my code). This is a generally better way to register event listeners as it allows multiple listeners and gives you automatic access to other info about the event that occurred.

How to apply style sheets to dynamically created elements?

this should be an easy one: I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(headRow);
table.appendChild(dataRow);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
The problem is: The style specified in the bootstrap.min for the class "table" is never applied upon loading the side. Do I have to do something additionally? I test it in the most recent version of Safari.
Any Help?
Cheers Twerp
It is not dynamically created issue. It is because you haven't set the class to table. As Bootstrap Docs says:
You have to use <thead> and <tbody> for the class to work.
To add in your answer:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Add this for a quick fix:
$("tr:first-child").wrap("<thead/>");
Your final code should look like:
var table = document.createElement("table");
table.setAttribute("id","table");
var headRow = document.createElement("tr");
var dataRow = document.createElement("tr");
var head = document.createElement("th");
var data = document.createElement("td");
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
head.innerHTML="head";
data.innerHTML="data";
headRow.appendChild(head);
dataRow.appendChild(data);
table.appendChild(thead);
table.appendChild(tbody);
console.log(document.styleSheets);
table.className = "table";
document.getElementById("test").appendChild(table);
The slight difference in styling is because Bootstrap relies on the <tbody> and <thead> elements to apply styling. If you're dynamically creating elements, you need to create these too:
var thead = document.createElement("thead");
thead.appendChild(headRow);
var tbody = document.createElement("tbody");
tbody.appendChild(dataRow);
Then, instead of appending headRow and dataRow directly, append the newly created elements:
table.appendChild(thead);
table.appendChild(tbody);
Example Fiddle
$(function () {
var table = $('<table></table>').attr('id', 'table').addClass('table')
var head = $('<th></th>').html('head')
var data = $('<th></th>').html('data')
var headRow = $('<tr></tr>').append(head)
var dataRow = $('<tr></tr>').append(data)
table.append(headRow)
table.append(dataRow)
console.log(document.styleSheets);
$('#test').append(table);
})
Best way to add style sheet to dynamically added content is to use classList
Please refer below link:
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
OR
You can use element.style.cssProperty

element.length returns 0 even if the element exist

The code below will dynamically create 5 table rows. I dont understand why td.length returns 0 even though I already created it. Can someone explains to me why?
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var table = $("#mytable");
for(var c=1; c<6; c++){
var id = "#row" + c;
var tr = $("<tr><td id="+id+">Row "+c+"</td></tr>");
table.append(tr);
}
var td = $("#row1");
alert(td.length);
});
</script>
</head>
<body>
<table id="mytable">
</table>
</body>
</html>
The id value itself should not contain the #.
Change this:
var id = "#row" + c;
to this:
var id = "row" + c;
The selector that you use with jQuery contains the #, but not the id value itself.

How to use createElement to create a new table?

Why the following code doesn't work?
<html>
<head>
<script type="text/javascript">
function addTable() {
var table = document.createElement('table');
table.innerHTML = "<tr><td>123</td><td>456</td></tr>";
document.getElementById("addtable").appendChild(table);
}
</script>
</head>
<body>
<input type="submit" value="New Table" onClick="addTable()"/>
<div id="addtable"></div>
</body>
</html>
To the best of my knowledge, setting the innerHTML property of a table element or table section element (like tbody or thead) does not work on Internet Explorer (EDIT: I just checked - with ietester and plain IE8. Result is "unknown runtime error" for IE6 and IE8, and it crashes IE7 but that might be an IEtester specific problem).
The DOM standard way of adding rows to a table is using the insertRow() method on a table or table section element (look for HTMLTableElement and HTMLTableSectionElement in that DOM spec) :
<script type="text/javascript">
function addTable() {
var c, r, t;
t = document.createElement('table');
r = t.insertRow(0);
c = r.insertCell(0);
c.innerHTML = 123;
c = r.insertCell(1);
c.innerHTML = 456;
document.getElementById("addtable").appendChild(t);
}
</script>
In the script, there is no explicit table section being created. AFAIK, a TBODY is automatically created, and rows are inserted in there.
EDIT: regarding IE, I should point out that you can add a table with content and all by setting the innerHTML property, but the html you inject in there must be a complete table. So this does work, even on IE:
<script type="text/javascript">
function addTable() {
var html = "<table><tr><td>123</td><td>456</td></tr></table>";
document.getElementById("addtable").innerHTML = html;
}
</script>
//_table my current table
var table = document.createElement('table'); //new table
table.innerHTML = _table.innerHTML; //clone table innerHTML

Categories