Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've got a JSON object that looks like this:
{"a": 1, "b": 3, "ds": 4}
I'd like to convert it into a HTML table that looks like this:
name | Value
a 1
b 3
ds 4
Could anyone tell me how to achieve this?
It's very simple with jQuery:
$(function() {
var jsonObj = $.parseJSON('{"a":1,"b":3,"ds":4}');
var html = '<table border="1">';
$.each(jsonObj, function(key, value) {
html += '<tr>';
html += '<td>' + key + '</td>';
html += '<td>' + value + '</td>';
html += '</tr>';
});
html += '</table>';
$('div').html(html);
});
Here is link to the working fiddle.
UPDATE: an alternative way to achieve this is by using a library called dynatable to convert the JSON into a sortable table.
You can use javascript:
<script type="text-javascript">
var data = {
"a": 1,
"b": 3,
"ds": 4
};
// Create a new table
var table = document.createElement("table");
// Add the table header
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = "Name";
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = "Value";
tr.appendChild(rightRow);
table.appendChild(tr);
// Add the table rows
for (var name in data) {
var value = data[name];
var tr = document.createElement('tr');
var leftRow = document.createElement('td');
leftRow.innerHTML = name;
tr.appendChild(leftRow);
var rightRow = document.createElement('td');
rightRow.innerHTML = value;
tr.appendChild(rightRow);
table.appendChild(tr);
}
// Add the created table to the HTML page
document.body.appendChild(table);
</script>
The resulting HTML structure is:
<table>
<tr>
<td>Name</td>
<td>Value</td>
</tr>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>3</td>
</tr>
<tr>
<td>ds</td>
<td>4</td>
</tr>
</table>
Here is the link to the working fiddle.
You should take a look at Knockout.js, with that, you can take your JSON data and bind it to HTML elements.
Updating is then done automatically, so you don't have to mess with that by yourself.
Here is a list of examples.
Related
I have an array of objects being displayed in a table... My goal is to access a specific item within the array by clicking on that item in the table. I would then be able to add/remove classes and access the values, which is ultimately what I need to do.
Here's where I'm stuck...
myArray.forEach((item, index) => {
// Sort through array, render to DOM
document.getElementById('myElementID').innerHTML +=
'<tr>' +
'<td>' +
item.thing +
'</td>' +
'<td' +
item.thing2 +
'</td>' +
'</tr>';
// Completely stuck... I've added an event listener to each table row.
addEventListener('dblclick', () => {
console.log(//I want to log the index of the item I just clicked on);
});
});
Please forgive me if this is very easy or I'm going about this all wrong, but I'm very new to all of this and I haven't been able to structure my question in such a way that google is helpful.
Thanks in advance.
EDIT - Some html as requested...
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
EDIT again (sorry) ... and a JS fiddle. You'll see that it logs both indexes, instead of just the one I clicked on. https://jsfiddle.net/c4pd5wmg/4/
Instead of messing with index etc.. you can attach the event handler to the tr and just reference e.target in the event handler. I also cleaned up your adding of tr.
const myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}]
myArray.forEach((item, index) => {
let row = document.createElement("tr");
let cell = document.createElement("td");
cell.innerHTML = item.number;
row.appendChild(cell);
cell = document.createElement("td");
cell.innerHTML = item.otherNumber;
row.appendChild(cell);
document.getElementById('myElementID').appendChild(row);
row.addEventListener('dblclick', (e) => {
console.log(e.target);
});
});
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
I have a html table
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
data here <3 ....
</tbody>
</table>
and here is my php (sample.php)
<?php
Query Code here..
Query Code there..
and so on
//this is the way I populate a table
while (query rows) {
echo '<tr>';
echo '<td>Sample Data</td>';
echo '</tr>;
}
?>
So to make this work and to populate the table this is what I do.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<?php
include 'folder_location/sample.php';
?>
</tbody>
</table>
Disregard the image of the ouput but when I go to Inspect Element or even Ctrl + u I will see my table structure now is like this.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<tr>
<td>Sample Data</td>
</tr>
</tbody>
</table>
Now here is the thing. I do not do that this is what I do.
$("#rpttable tr").remove();
for (i = 0; i < data.length; i++) {
tr = $("<tr />");
for (x in data[i]) {
td = $("<td />");
td.html(data[i][x]);
tr.append(td);
}
rpttable.append(tr);
}
Same output It does populate the table but when I go to Inspect Element or even Ctrl + u the output is.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
**This is the part missing**
</tbody>
</table>
My question here is how can I literaly create an element usung javascript/ajax? same output in php. I mean write the element.
** Updated **
I am trying to run a css class from an external file and If I manualy edit it to suits my needs I will a long hour and also Its hard for me to explain its a class for table. I tried to use that class using default value in <table>. You know manualy write it at the back end. now Im trying to populate it using a php and ajax so, so far so good it does populate but when I try to run the class the class does not work.
TYSM
Using jquery you can add html rows to the tbody using:
$("#rptbody").html("<tr><td>value</td></tr>");
Is this what you want to do?
You can use JQuery append() method:
$('#rptbody').append('<tr><td>my data</td><td>more data</td></tr>');
In case you need to insert after last row:
$('#rptbody> tbody:last-child').append('<tr>...</tr><tr>...</tr>');
for (i = 0; i < 5; i++) {
let tr = $("<tr />");
for (j=0; j < 5;j++)
tr.append($("<td />",{html:j,class:"tbl"}));
$("tbody").append(tr);
}
.tbl{border:1px solid pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
You have asked roughly two questions. Let's break it down.
My question here is how can I literaly create an element usung javascript/ajax?
You are already doing this with your Javascript (client-side) code. It looks like you're using jQuery syntax, so we'll stick with that. This does create an element and inserts it into the page.
var $el = $("<div>I'm a new div element</div>");
$('body').append( $el );
This creates a new element, assigns it to the $el variable, and then appends it to the body of the page. This will not show up in "View Page Source" view, however. Why? Because this modifies the DOM -- the Dynamic Object Model.
To see this new element, you'll either need to look at the rendered output (what the user/you sees), or open up your browser's DevTools (often <F12>, or right-click -> inspect). In the DevTools, find the "Inspector" tab (or equivalent), then look for your new element in this live view of the DOM.
... same output in php.
In short, you can't. What Ctrl+U / View Page Source shows is the page as it was initially received from the server. This would be the exact content you would see if you were to use a command line tool, like curl or wget:
curl http://url.to.your.com/page
Since you include 'folder_location/sample.php' at the server, this is included in the page before the browser sees it. For your edification, I would consider reading up on the DOM.
Wikipedia
W3
Try this:
$("#rpttable tbody tr").remove();
var content = '' ;
for (i = 0; i < data.length; i++) {
content += "<tr>" ;
for (x in data[i]) {
content += "<td>" + data[i][x] + "</td>" ;
}
content += "</tr>" ;
}
$("#rpttable tbody").html(content) ;
Updated
I am using Google Chrome too. Please try the below code, and check the inspect element each time you add a new row. You can see the html in the Inspect Element changing!
function AppendNewRowToTable() {
var trLen = $("table tbody tr").length ;
var content = "" ;
content += "<tr>" ;
for (i = 0; i < 5; i++) {
content += "<td>" + trLen + "-" + i + "</td>" ;
}
content += "</tr>" ;
$("table tbody").append(content) ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add new Row
<br />
<table>
<thead>
<tr>
<th>Title 01</th>
<th>Title 02</th>
<th>Title 03</th>
<th>Title 04</th>
<th>Title 05</th>
</tr>
</thead>
<tbody></tbody>
</table>
It seems your intent is to append extra rows to the table in your html response generated from your PHP script.
For that you don't need to clear all existing rows.
$("#rpttable tr").remove();
Build an array of rows and append once to your table body.
var $tbody = $('#rptbody');
var tableRowAdditions = [];
for (var i = 0; i < data.length; i++) {
var $tr = $("<tr></tr>");
for (var x in data[i]) {
var $td = $("<td></td>");
$td.html(data[i][x]);
$tr.append(td);
}
tableRowAdditions.push(tr);
}
$tbody.append(tableRowAdditions);
For a "pure" JavaScript approach, you can create elements using the createElement Web API
For example:
A paragraph with text "Hello" would be
var container = document.getElementById('rptbody');
var hello = document.createTextNode('Hello');
var helloParagraph = Document.createElement('p');
// Add text to paragraph
helloParagraph.appendChild(hello);
// Append to container
container.appendChild(helloParagraph);
The best way to create elements using jQuery is to use the following format:
// Create the TR and TD elements as jQuery objects.
var tr = $("<tr></tr>", {
"id":"tr1",
"class":"tr"
});
var td = $("<td></td>", {
"id":"td1",
"class":"td",
"text": "Sample Data",
click: function() {
// optional: Function to attach a click event on the object
alert("Clicked!");
}
});
// Attach the element to the document by appending it
// inside rptbody (after all existing content inside #rptbody)
$("#rptbody").append(tr);
tr.append(td);
// OR, Attach the element to the document by prepending it
// inside rptbody (before all existing content in #rptbody)
$("#rptbody").prepend(tr);
tr.append(td);
// OR, Attach the element to the document by completely replacing the content of #rptbody
$("#rptbody").html(tr);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
</tbody>
</table>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I want to fill my HTML table with my array. I tried it with $rowTemplate.find('[data-id=id]').text(id);
But it didn't work. I work with sockets so I can't post all of my code that would be too confusing.
I will ads some of my code but it's a general question how to fill a HTML table with input of an two dim array.
socket.on('outputData', function(data) {
var $rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
var resultArray = data.resultArray;
var name, location, bdate, id, anzahl = 0;
for (var i = 0; i < resultArray.length; i++) {
name = resultArray[i][0];
anzahl = anzahl + 1;
console.log(name);
location = resultArray[i][1];
bdate = resultArray[i][2];
favorit = resultArray[i][3];
id = resultArray[i][4];
$rowTemplate.find('[data-id=id]').text(id);
$rowTemplate.find('[data-id=name]').text(name);
$rowTemplate.find('[data-id=geburtsort]').text(location);
$rowTemplate.find('[data-id=geburtsdatum]').text(bdate);
}
$("#table > tbody").append(rowTemplate.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table id="table">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Geburtsort</th>
<th>Geburtsdatum</th>
<th>Favorit</th>
</tr>
</tbody>
</table>
The problem lies with your variable rowTemplate. Get rid of the $ and it should work.
var rowTemplate = $('<tr><td data-id="id"></td><td data-id="name"></td><td data-id="geburtsort"></td><td data-id="geburtsdatum"></td><td data-id="favorite"></td></tr>');
rowTemplate.find("[data-id=id]").text("bcd");
Test it out here: https://jsfiddle.net/Lwmu4p6q/
I am not quite sure why that is the case, though. I think it is problematic because of jQuery. You can still use variables starting with a dollar sign, but when you start cascading with jQuery functions, it doesn't seem to work.
EDIT: Another way to do it would be to manually "build up" the row.
Instead of parsing the HTML with jQuery like rowTemplate = $('...'); and then manipulating it with jQuery selectors you could do it like this with vanilla JavaScript:
var outputHTML = "";
for (var i = 0; i < array.length; i++) { // i for the rows
var newRow = "<tr>";
for (var j = 0; j < array[i].length; j++) { // j for the colums
newRow += "<td>" + array[i][j] + "</td>";
}
outputHTML += newRow + "</tr>";
}
I would suggest using let instead of var if possible. And I would argue that this version might perform faster, but the difference, if existent at all, would only matter with really big tables. It depends on the way jQuery selectors and text() has been implemented, though.
EDIT 2:
Check https://jsfiddle.net/Lv9vdv8u/ for the second version.
I have a table which looks essentially like this
<!DOCTYPE html>
<html lang="en">
<body>
<table class="ui table" id="items">
<tbody>
<tr data-toggle="fieldset-entry">
<td><input id="items-0-quantity" name="items-0-quantity" type="text" value=""></td>
<td><input id="items-0-description" name="items-0-description" type="text" value=""></td>
</tr>
</body>
</html>
Using javascript, I'd like to have a button which adds a new row to the table, and I'd like the inputs in that new row to have id="items-1-xxx", and name="items-1-xxx, i.e. where there's a 0 in the original row I'd like a 1 in the new row.
I can make a new table row by cloning the old one, but I have not figured out how to modify the name and id attributes of the input.
Here's a sketch of what I've tried:
function cloneRow() {
var table = document.getElementById("items");
var original_row = table.rows[table.rows.length - 1];
var new_row = original_row.cloneNode(true);
// We have a new row and now we need to modify it as
// described in the question. The only way I've found
// is to grab the inner HTML:
var cell_contents = original_row.cells[0].innerHTML;
// Now we could do a bunch of string parsing and manipulations
// to increment the 0 to a 1 and stuff the modified HTML into
// new_row, but it seems there must be a better way.
// Finally insert the new row into the table.
original_row.parentNode.insertBefore(new_row, original_row.nextSibling);
}
What is the right way to update the input elements' id and name?
You could just build a new <td> and assign document.querySelectorAll('#items tr').length as the x in items-x-...:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length
, newitemQuantityText = 'items-' + itemcount + '-quantity'
, newitemDescriptionText = 'items-' + itemcount + '-description'
, newitem = document.createElement('tr')
, newitemQuantity = document.createElement('td')
, newitemDescription = document.createElement('td')
, newitemQuantityInput = document.createElement('input')
, newitemDescriptionInput = document.createElement('input');
newitemQuantityInput.id = newitemQuantityText;
newitemQuantityInput.name = newitemQuantityText;
newitemQuantity.appendChild(newitemQuantityInput);
newitemDescriptionInput.id = newitemDescriptionText;
newitemDescriptionInput.name = newitemDescriptionText;
newitemDescription.appendChild(newitemDescriptionInput);
newitem.appendChild(newitemQuantity);
newitem.appendChild(newitemDescription);
document.querySelector('#items').appendChild(newitem);
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items"></table>
However using good old innerHTML reads way better:
function addItem() {
var items = document.querySelector('#items')
, itemcount = items.querySelectorAll('tr').length;
items.innerHTML += '<tr><td>' +
'<input id="item-' + itemcount + '-quantity" name="item-' + itemcount + '-quantity">' +
'</td><td>' +
'<input id="item-' + itemcount + '-description" name="item-' + itemcount + '-description">' +
'</td></tr>';
}
document.querySelector('#add').addEventListener('click', addItem);
<button id="add">add item</button>
<table id="items">
</table>
You can separately reconstruct the node itself by using
createAttribute()
createElement()
Fiddle: http://jsfiddle.net/ztb9gq3d/1/
This is not the data oriented approach the question asks for, but a reasonably simple solution is
numRows = table.rows.length;
// Use a regexp so we can replace all instances of the number
// corresponding to what is currently the last table row.
var re = new RegExp((numRows - 1).toString(), "g")
for (var i = 0; i <= originalRow.cells.length - 1; i++) {
var originalHTML = originalRow.cells[i].innerHTML;
var newHTML = originalHTML.replace(re, numRows.toString());
newRow.cells[i].innerHTML = newHTML;
}
Obviously this only works if the number we replace doesn't exist elsewhere in the HTML string, so this is not a particularly good solution.
However, we could use a more complex regexp.
This solution does have the advantage that we don't need to hard-code anything except the parts we want to replace into the regexp.
Therefore, if the HTML in the table were to acquire additional parts in future development this solution will still work, up to the quality of the regexp as already mentioned.
I'm trying to do my best effort planning how to do this but I can't...
Example:
I have a table with id, but not td id's...
I have four td's en each tr.
<tr>
<td>one</td><td>two</td><td>three</td><td>four</td></tr>
<tr>
<td>aaa</td><td>bbb</td><td>ccc</td><td>ddd</td></tr>
So, what I want is to generate in the same table this output:
<tr>
<td>one two</td><td>three four</td></tr>
<tr>
<td>aaa bbb</td><td>ccc ddd</td></tr>
From 4 td to 2 td in the table showing the four values.
Edit: I misread your target HTML and gave you something you weren't looking for. Here's the corrected code that gives you the HTML result you want:
http://jsfiddle.net/gilly3/DxVAS/6/
var t = document.getElementById("myTable");
for (var i = t.rows.length - 1; i >= 0; i--) {
var r = t.rows[i];
r.cells[0].innerHTML += " " + r.removeChild(r.cells[1]).innerHTML;
r.cells[1].innerHTML += " " + r.removeChild(r.cells[2]).innerHTML;
}
Have fun: http://jsfiddle.net/ungarida/4C29u/