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>
Related
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 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.
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)
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
Is there a plugin or way to make certain table columns (not rows) editable and others not editable
with jQuery?
I have seen plugins for clicking on a cell to make it editable, but I mean explicitly making a cell/column editable or not.
I have a way of doing it but it feels like a bit of a hack job.
Here is my function for making a column editable:
function isEditable(rowArray, headersArray)
{
var counter = 0;
var notEditable = ['product code', 'product'];
for(i in rowArray){
counter = 0;
data = headersArray[i].toLowerCase();
for(a in notEditable){
if(data == notEditable[a]){
counter++;
}
}
if(counter > 0){
rowArray[i] += 'notEditable';
}
}
return rowArray;
}
it compares the header of the cell to an array of predefined values which = a non-editable column.
Then I build the row:
function buildHTMLTableRow(row, mutable)
{
output = '';
output += '<tr>';
for(var i = 0; i < row.length; i++)
{
value = trim(row[i]);
if(mutable){
index = value.indexOf('notEditable');
if(index != -1){
value = value.substring(0, index);
output += '<td>' + value + '</td>';
}
else{
output += '<td><input size="5" type="text" value="' + value + '" /></td>';
}
}
else{
output += '<td>' + value + '</td>';
}
}
output += '</tr>';
return output;
}
The mutable parameter decides if the row is editable or not, and the indexOf('noteditable') decides for the cell(but pretty much column) from the isEditable function.
Is there a plugin that does this better, or should I just settle with what I have?
Visit this jsFiddle link: Disable Columns
Following is the data flow:
I have created a row Array named "rowsD". When page loads I am populating my table (id=myData) with these rows.
Now creating another array called disableHeaders wherein I am passing the headers,
which you need to disable entire columns.
I am calling function disableFields passing disableHeaders as parameter
In the function, first I am fetching the index of the header whose value is equal to the values in headers array
If I find one, then from Input tag I am extracting the Value attribute using $(this).find('input') selector
Finally I am replacing the current child with Label tag passing the extracted Input tags Value
You may also comment out disableFields(disableHeaders); line to actually see, how table gets rendered initially
Thank you