I want to populate a predefined html table using JavaScript:
<table>
<tr>
<th scope="col">ID</th>
<th scope="col">Name</th>
</tr>
<div id='data'/>
</table>
using
document.getElementById('data').innerHTML = ....
But since <div> is not allowed inside of <table> above code doesn't work. What is the correct way to achieve this?
Instead of Div you can use tr and td.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html>
<head>
<script type="text/javascript">
function addRow(content,morecontent)
{
if (!document.getElementsByTagName) return;
tabBody=document.getElementsByTagName("tbody").item(0);
row=document.createElement("tr");
cell1 = document.createElement("td");
cell2 = document.createElement("td");
textnode1=document.createTextNode(content);
textnode2=document.createTextNode(morecontent);
cell1.appendChild(textnode1);
cell2.appendChild(textnode2);
row.appendChild(cell1);
row.appendChild(cell2);
tabBody.appendChild(row);
}
</script>
</head>
<body>
<table border='1' id='mytable'>
<tbody>
<tr><td>22</td><td>333</td></tr>
<tr><td>22</td><td>333</td></tr>
</tbody>
</table>
<button onClick='addRow("123","456");return false;'>
Add Row</button>
</body>
</html>
In the most basic sense:
<table>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td colspan="2">
<div> LOTS O' CONTENT </div>
</td>
</tr>
</table>
You've answered yourself - put the div in the right location - either inside the table or outside. The javascript will work, whether the div will be displayed where you'd like it to, is a different question :)
Related
in node js i try to render table tr with iterate function but it shows unexpected token "<". check the given code snippet. in table row tr i want it iterate dynamically.
module.exports = ({p}) => {
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<table class="table-bordered">
<thead>
<tr>
<th>Product</th>
<th class="w-20">Price</th>
<th class="w-20">Quantity</th>
<th class="w-20">Total</th>
</tr>
</thead>
<tbody>
**// want to iterate below <tr>**
<tr>
<td>${p.name}</td>
<td>${p.price}</td>
<td>${p.quantity}</td>
<td>${p.price * p.quantity}</td>
</tr>
<tr>
<td colspan="3" class="text-right">Sub Total</td>
<td> ${p.subTotal}</td>
</tr>
</tbody>
</table>
please help me how can i overcome to solve this issue
Use something like this :-
Map over array of p and produce array of tr for each p.
Then, append it to main html
module.exports = ({
ArrayOfP
}) => {
const allTr = ArrayOfP.map(p =>(`<tr>
<td>${p.name}</td>
<td>${p.price}</td>
<td>${p.quantity}</td>
<td>${p.price * p.quantity}</td>
</tr>`))
}
return `
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<table class="table-bordered">
<thead>
<tr>
<th>Product</th>
<th class="w-20">Price</th>
<th class="w-20">Quantity</th>
<th class="w-20">Total</th>
</tr>
</thead>
<tbody>
**// want to iterate below <tr>**
${allTr.join("")}
<tr>
<td colspan="3" class="text-right">Sub Total</td>
<td> ${p.subTotal}</td>
</tr>
</tbody>
</table>`
}
I tried several method to delete a row from the table with specific Id. Here is the table structure:
I tried to use closest as follow
$(this).closest('tr').remove();
and I tried to use this Also
var index=Id.parentNode.parentNode.rowIndex;
To find the row index and then delete but I get uncought error parentNode is not defined and closest is not reacting at all..
Any idea on how to solve this issue?
Since question is not tagged with jquery here is an example of deleting table rows using just JavaScript:
function handleClick(event) {
// react only to button clicks
if (event.target.className == 'itemToDelete') {
// get row containing clicked button
var row = event.target.parentNode.parentNode;
// remove row element
row.parentNode.removeChild(row);
}
}
window.addEventListener('DOMContentLoaded', function() {
// register click handler for whole table for efficiency
document.querySelector('.table').addEventListener('click', handleClick, false);
}, false);
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table class="table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>Doe</td>
<td>
<button type="button" class="itemToDelete">Delete row</button>
</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
<td>
<button type="button" class="itemToDelete">Delete row</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
use jquery
$(".itemToDelete").click(function(){
$(this).closest("tr").remove();
});
Try to set id in table row
You can remove by jquery$("#"+id).remove();
General info: I am trying to make a table using the JQuery mobile. Up to this point my table looks good however, I have some minor issues.
Here is the code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<style>
th
{
border-bottom: 1px solid #d6d6d6;
}
tr:nth-child(even)
{
background:#e9e9e9;
}
</style>
</head>
<body>
<h1>My Name</h1>
<div data-role="page" id="pageone">
<div data-role="header">
<h1> Cs496 Hw2</h1>
<h2> By: My Name here</h2>
</div>
<div data-role="main" class="ui-content">
<table data-role="table" data-mode="columntoggle" class="ui-responsive ui-shadow" id="myTable">
<thead>
<tr>
<th data-priority="1">No.</th>
<th>School Name</th>
<th data-priority="2">LOGO</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="schoolName_0">schools[0].name</td>
<td id="schoolImage_0">schools[0].image</td>
</tr>
<tr>
<td>2</td>
<td id="schoolName_1">schools[1].name</td>
<td id="schoolImage_1">schools[1].image</td>
</tr>
<tr>
<td>3</td>
<td id="schoolName_2">schools[2].name</td>
<td id="schoolImage_2">schools[2].image</td>
</tr>
<tr>
<td>4</td>
<td id="schoolName_3">schools[3].name</td>
<td id="schoolImage_3">schools[3].image</td>
</tr>
<tr>
<td>5</td>
<td id="schoolName_4">schools[4].name</td>
<td id="schoolImage_4">schools[4].image</td>
</tr>
<tr>
<td>6</td>
<td id="schoolName_5">schools[5].name</td>
<td id="schoolImage_5">schools[5].image</td>
</tr>
<tr>
<td>7</td>
<td id="schoolName_6">schools[6].name</td>
<td id="schoolImage_6">schools[6].image</td>
</tr>
</tbody>
</table>
<script type='text/javascript'>
function school(name,image){
this.name = name;
this.image = image;
}
var schools = [
new school('Oregon State University', "http://www.sports-logos-screensavers.com/user/OregonStateBeavers.jpg"),
new school('University of Oregon', "http://www.sports-logos-screensavers.com/user/Oregon_Ducks06.jpg"),
new school('Stanford University', "http://www.sports-logos-screensavers.com/user/Stanford_Cardinal.jpg")
new school('University of Southern California', "http://www.sports-logos-screensavers.com/user/USC_Trojans2.jpg"),
new school('University of Washington', "http://www.sports-logos-screensavers.com/user/Washington_Huskies2.jpg"),
new school('San Diego State University', "http://www.sports-logos-screensavers.com/user/SanDiegoStateAztecs3.jpg"),
new school('Florida State University', "http://www.sports-logos-screensavers.com/user/FloridaStateSeminoles.jpg")
];
</script>
</div>
</body>
</html>
Q: What I want to do is use Jquery to insert the contents of the schools array into the correct columns and rows. I wanted to do this by making an array of objects and then insert the associated element in the correct location in the table (where logos are links to images).
I have tried using both Jquery's append and appendto commands in the script portion of my html but that did not work. Also I tried using the document.getElementbyId(...) but that did'nt work either. I believe the script portion of my html is never being called.
Any Ideas are welcome.
The reference to schools[x].name and schools[x].image is not how javascript, or jQuery for that matter, will execute those. Infact this is probably rendering as straight text in your html <td> tags rather than the array element value you are hoping for.
Here is what I would do.
First, add an appropriate class to each of the <td> elements, and a rel attr to hold the counter like so:
<tr>
<td>1</td>
<td class='name' rel='0'></td>
<td class='image' rel='0'></td>
</tr>
Then, iterate over each of the <td> elements in the table, using the rel tag as the array index to retrieve the values from; finally, apply the values to the <td> tags with the .html('...') function, like so:
$.each( $("table#myTable tr td"), function(i,e){
var $this = $(this), //set $(this) object to a variable rather than referencing it multiple times
rel = parseInt( $this.attr('rel') );
//only look for td elements that have a class
if( $this.hasClass('name') )
$this.html( schools[ rel ].name );
if( $this.hasClass('image') )
$this.html( '<img src="' + schools[ rel ].image + '"/>' );
});
I haven't tested this, but I think the logic is sound...
Note: this is meant to be a community wiki post
The following code using simple dom methods fails to add rows to the table. What's the issue?
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytable = document.getElementById('mytable');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytable.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tr>
<td>This is a row</td>
</tr>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
The issue at hand here is that the <table> element's correct structure is not present. When dealing with tables, the basic structure is:
<table>
<thead>
<tr>
<th>Heading for the table</th>
</tr>
</thead>
<tbody>
<tr>
<td>A row of data</td>
</tr>
</tbody>
</table>
The logic is that when dealing with tables, you want to keep the labels of the columns, and the actual data separate. Because most browsers fill in the <tbody> as part of the process of fixing broken HTML, few people realize this. When the browser sees you adding a <tr>, it doesn't know if you're trying to add it to the <thead> or the <tbody>, so it fails.
The following shows the correct method for adding the rows:
<html>
<head>
<title>Javascript Test</title>
<script>
function addRow() {
var mytbody = document.getElementById('mytbody');
var row = document.createElement('tr');
var cell = document.createElement('td');
var text = document.createTextNode('This is a row');
cell.appendChild(text);
row.appendChild(cell);
mytbody.appendChild(row);
}
</script>
</head>
<body>
<form action="#">
<table id="mytable">
<tbody id="mytbody">
<tr>
<td>This is a row</td>
</tr>
</tbody>
</table>
<input type="button" onclick="addRow()" value="Add A Row"/>
</form>
</body>
</html>
Any additional row needs to be added then take the first child of tableID and then use appendChild() method:
var tbl=document.getElementById("tbl");
var row=document.createElement("tr");
var cel=document.createElement("td");
cel.innerHTML='sometext';
row.appendChild(cel);
tbl.children[0].appendChild(row);
how can i append a new tr to the top of the table instead of under other tr.
Example:
<table width='100%'>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>
After a click event in jQuery, how can i place
<tr><td>something3</td><td>else here3</td></tr>
at the top of the table so it now looks like
<table width='100%'>
<tr><td>something3</td><td>else here3</td></tr>
<tr><td>something</td><td>else here</td></tr>
<tr><td>something2</td><td>else here2</td></tr>
</table>
Any help on this would be greatly appreciated.
$('table').prepend('<tr><td>something3</td><td>else here3</td></tr>');
or...
$('<tr><td>something3</td><td>else here3</td></tr>').prependTo('table');
More info on 'prepend': http://docs.jquery.com/Manipulation/prepend
More info on 'prependTo': http://docs.jquery.com/Manipulation/prependTo
This JS is IE specific at the moment, but it shouldn't be too hard to make it multi-browser compatible.
<html>
<body>
<script language="JavaScript">
function function1() {
var myRow = document.all.myTable.insertRow(0);
var myCell = myRow.insertCell();
myCell.innerText = "The added cell";
}
</script>
<table id="myTable" border="1" cellspacing="5" cellpadding="5">
<tr>
<td width="100">3</td>
<td width="100">4</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>
<button onclick="function1();">Add a cell</button>
</body>
</html>