What I'm trying to do is pretty simple: Add a 1x20 table of input cells inside a div.
I created a JavaScript function
var tableHTML = function(attributes, rows, columns)
{
var retHTML = "<table " + attributes + ">";
for (var i = 0; i < rows; ++i)
{
retHTML += "<tr>";
for (var j = 0; j < columns; ++j)
retHTML += "<td> </td>";
retHTML += "</tr>";
}
return (retHTML + "</table>retHTML");
}
to give me the HTML for a table with a specified dimensions and attributes. Then, in the body of my HTML, I put
<div class="inner_div" id="input_table">
<!-- div to house the table -->
</div>
<script type="text/javascript">
document.getElementById("input_table").innerHTML += tableHTML("id=\"input_table\" type=\"input\"", 1, 20);
</script>
which I thought would accomplish the task, but hasn't. I think this is because I'm trying to assign a string object to an HTML object. I kinda assumed that an implicit cast would be made. Anyways, I'm wondering if anyone has a "quick fix" to my problem. I would prefer not to redo my entire approach to the problem, but I also wouldn't mind someone informing me of the proper way to do the type of thing I'm trying to do -- using JavaScript to fill in page HTML on load.
Here's my take on this. I'm learning functional programming, so I do a bunch things here that might seem like their a waste of coding, but here's the concept:
Get the dimensions
Create a single row
Copy that row to make the table
After that return the table.
If you want to add id's, class's, etc... work with the DOM element returned by makeTable.
// Makes a single row
var makeRow = function(_columns) {
var row = document.createElement('tr');
var cell = document.createElement('td');
var cols = _columns;
while (cols) {
row.appendChild(cell.cloneNode(true));
cols--;
}
return row;
}
// Makes a table
var makeTable = function(_rows, _columns) {
var table = document.createElement('table');
var row = makeRow(_columns);
var rows = _rows;
while (rows) {
table.appendChild(row.cloneNode(true));
rows--;
}
return table;
}
I tried your code and it works: the table is generated and obviously empty
But be carrefull: if you do this, you will have two elements with the same ID (input_table)
Related
I'm kinda lost in figuring out the logic for javascript.
Currently, I'm extracting every element and pushing them into an array.
I'm having a hard time when I want to access the object element.
This is the data in the text file:
1#1#test#Tombstone#8#Yes
2#3#test2#Tombstone3#81#Yes
When I access the first array rowCells[0] . It returns me
1
2
which is the first column itself.
I was hoping for it to return the first row. The intended functionality is as follows:
1- Push everything to an array
2- Giving element key like first column is no,type,header,content,score
3- Search all the row based on the element key such as type=2
4- Search based on the type and no, then show the content.
Any suggestions?
Thanks in advance.
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$.ajax({
url: 'content.txt',
dataType: 'text',
}).done(successFunction);
function successFunction(data) {
var allRows = data.split(/\r?\n|\r/);
var table = '<table>';
for (var singleRow = 0; singleRow < allRows.length; singleRow++) {
var rowCells = allRows[singleRow].split('#');
//table += rowCells.toString();
table += '<br>';
var first_word = rowCells;
table += first_word;
}
$('body').append(table);
}
</script>
I would just use split, reduce, split, and join to build the table.
var str = `1#1#test#Tombstone#8#Yes
2#3#test2#Tombstone3#81#Yes`
var rows = str.split(/\n/g).reduce( function (str, row) {
return str + "<tr><td>" + row.split(/#/g).join("</td><td>") + "</td></tr>";
}, "")
var table = "<table><tbody>" + rows + "</tbody></table>"
$("#out").append(table)
td { border: 1px solid black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="out"></div>
I want to create a webpage that loads a selected CSV file (from hard drive) and displays its contents using table HTML.
The project incorporates two components and so far, I've been researching the latter; generating a table out of a nested array in javascript.
For some reason, the columns do not appear the way they should.
My code
<!DOCTYPE html>
<html>
<body>
<table id="1"> </table>
<button onclick="createTable()">Create</button>
<script>
function createTable() {
var array = [[1,2,3],[4,5,6],[7,8,9]];
document.getElementById("1").innerHTML = ""; //Clear.
for (i = 0; i < array.length; i++) {
document.getElementById("1").innerHTML += "<tr>";
for (k = 0; k < array[0].length; k++) {
document.getElementById("1").innerHTML += "<td>" + array[i][k] + "</td>" ;
}
document.getElementById("1").innerHTML += "</tr>";
}
}
</script>
</body>
</html>
Save the table contents to a variable first and set it to the innerHTML afterwards. Everytime you add a <tr> (or any not singleton tag for that matter), the browser immediately renders the closing tag.
Try this:
function createTable() {
var array = [[1,2,3],[4,5,6],[7,8,9]];
var content = "";
array.forEach(function(row) {
content += "<tr>";
row.forEach(function(cell) {
content += "<td>" + cell + "</td>" ;
});
content += "</tr>";
});
document.getElementById("1").innerHTML = content;
}
Because you are planning on using the FileReader API, IE9 support is off the table anyways. Updated the above function to use the 'newer' forEach array function
ADDENDUM
To load a file with javascript you have to use the FileReader HTML5 API. I can give you some pointers as to how you should go about doing this. This is all untested code, but it gives you a little idea what to do
1.Create a input field
<input type="file" id="file" name="file">
2.Trigger a response on change of this input
var file = document.getElementById('file');
file.addEventListener('change', function() {
var reader = new FileReader();
var f = file.files[0];
reader.onload = function(e) {
var CSVARRAY = parseResult(e.target.result); //this is where the csv array will be
};
reader.readAsText(f);
});
3.Parse the result to an array by using split/push. This uses \n as row delimiter and , as cell delimiter.
function parseResult(result) {
var resultArray = [];
result.split("\n").forEach(function(row) {
var rowArray = [];
row.split(",").forEach(function(cell) {
rowArray.push(cell);
});
resultArray.push(rowArray);
});
return resultArray;
}
(or you can use a third party plugin which will parse the CSV for you: papa parse, for instance)
After some long searching, this is probably the most simple and functional script that I could ever come across, also available for free. Although it doesn't deal with the array modification directly, it's easy to edit and elicit your desired results.
I have created ten separate tables in javascript using HTML tags. I now want to put those tables in a grid format so I thought putting them into another table would work. This code just makes an empty table appear. Any help? Thanks!
document.getElementById('InstalledApps').innerHTML += '<table id="bigAppsTable" border="1"><td>';
for (var i = 9; i>-1;i--){
document.getElementById('InstalledApps').innerHTML += '<table id="appsTable'+i+'" border="1"><tr></tr>';
var thirdRow=document.getElementById("appsTable"+i).insertRow(1);
if (the_data[i]['release'] != null){
thirdRow.insertCell(-1).innerHTML="<b>Release: ";
thirdRow.insertCell(-1).innerHTML=the_data[i]['release'];
}
var secondRow=document.getElementById("appsTable"+i).insertRow(1);
secondRow.insertCell(-1).innerHTML="<b>Version: ";
secondRow.insertCell(-1).innerHTML=the_data[i]['version'];
var firstRow=document.getElementById("appsTable"+i).insertRow(1);
firstRow.insertCell(-1).innerHTML="<b>Name:";
firstRow.insertCell(-1).innerHTML=the_data[i]['name'];
}
Since you're dynamically creating tables, why not use the DOM API? (ie. not innerHTML)
Here is a good place to get your started: https://developer.mozilla.org/en-US/docs/Web/API/document.createElement
Try like this
var aTable = document.createElement('table');
for (var i = 0, tr, td; i < 9; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode("some text"));
tr.appendChild(td);
aTable.appendChild(tr);
}
//update with id
document.getElementById('table').appendChild(aTable);
I have this JSON which generates a table :
function show(json)
{
var content = '<table id = "myTable" border = 1>';
var counter;
for(counter = 0; counter < json.length ; counter++)
{
content += '<tr><td class = "topics">' + json[counter]['topic_name'] + '</td>''</tr>';
}
content += '</table>';
$('#table_here').append(content);
}
I call it two times :
1st. here :
$(document).ready(function(){
$.getJSON("admin.php", show);
Second when I add something on the table:
When I add something, the new table appears below the old one, I want to lose the old one and see only the new one. How can I do it?
try to change
$('#table_here').append(content);
into
$('#table_here').html(content);
this will replace the entire content of #table_here element
I've been having a hard time trying to append new headers to tables I build dynamically using data grabbed from an AJAX call.
I've already asked here a question about my problem, but it seems that there's no logical answer to it.
So my problem is that I can't actually get the table I want to append my new info to, what I tired was this:
console.log(id); //This prints the right id!
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
//$('#'+401+' tr:first').append("<td>Well "+(wellCounter)+"</td>");--this will work
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
But it didn't work, so I was wondering if you can help me with another way to get the same functionality without using the id to get the table. Maybe the closest function will work but I don't have experience with that, and I tried it but failed.
Here the full code:
$.each(data, function(index, firstLevel) {
$.each(firstLevel, function(index2, secondLevel) {
var id = firstLevel['id'];
var author = firstLevel['author'];
var date = firstLevel['date'];
var experimental_conditions = firstLevel['experimental_conditions'];
if(index2 == 'items'){
var table = '<div class=tableWrapper><table id=\"'+id+'\" class=\"experimentTable\">';
table += '<input id=\"basketButton\" type=\"submit\" value=\"Add to basket\" class=\"basketButton\" experimentBatch=\"'+id+'\"> <div class="superHeader"><span class=\"superHeader\">Date: '+date+', By '+author+'</span><br /><span class=\"subHeader\">Experimental conditions: '+experimental_conditions+'</span>'
table += '<tr><td></td><td COLSPAN=2>Totals</td></tr>';
table += '<tr id="header"><td width="20%">Genotype</td><td width="10%"><img src="images/herma.png"></td><td width="10%"><img src="images/male.png"></td>';
//for each table
$.each(secondLevel, function(index3, thirdLevel) {
var nWells = 0;
table += "<tr><td>"+thirdLevel['mutant_name_c']+"</td><td>"+thirdLevel['herm_total']+"</td><td>"+thirdLevel['male_total']+"</td>";
currentRow = 3;
wellCounter = 0;
//for each row
$.each(thirdLevel, function(index4, fourthLevel) {
wellCounter++;
if (fourthLevel.date_r != undefined){
console.log(id);
//THIS is not working...
$('#'+id+' tr:first').append("<td>Well "+(wellCounter)+"</td>");
//...
table+="<td>M "+fourthLevel.male+"</td>";
table+="<td>H "+fourthLevel.herm+"</td>";
}
});
});
table +='</table></div>'
$('#searchResults').append(table);
}
});
});
NOTE: Male and herm are worm genders, not options!
I didn't go through your code, but when I'm working with dynamic table in jquery i try with Jquery "OBJECT". something like
var $tbl = $('<table />'), $tr=$('<tr />'), $td=$('<td />');
then you can add attr, append etc, and is much easier to read, and manipulate.
$tbl.attr('id',id).append($tr.append($td);
etc.