Turn several strings of structured text into HTML table [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
For example I have the following text with no tags at all within the HTML page:
Color: red
Shape: square
Side: 1mm
As much rows as needed, but three is quite enough for this question. Even one would be.
In those rows I'll always have the beginning of the text string, colon+space (: ) and the end of the text string.
How should I turn the beginning of the text string into <tr><td>, colon+space into :</td><td> and the end of the text string into </td></tr>?
Thanks to #Andrew Willems (the script) and #Phil (further suggestions) everything is up and running.

The original text here has some extra unnecessary lines before and after the text to demonstrate the need for dealing with, and the ability to deal with, extra lines.
var opening = '<table id="newborn_table"><tbody>';
var closing = '</tbody></table>';
var origText = document.querySelector('#source').innerText;
var lines = origText.split('\n').filter(function(line) {
return (line !== "");
});
var rowsText = '';
lines.forEach(function(line) {
var parts = line.split(': ');
rowsText +=
'<tr><td>' +
parts[0] +
'</td><td>' +
parts[1] +
'</td></tr>'
});
document.querySelector('#result').innerHTML =
opening + rowsText + closing;
#newborn_table td {
border: solid red 1px;
}
<p>Original text:<p>
<pre id="source">
Color: red
Shape: square
Side: 1mm
</pre>
<p>Parsed table:</p>
<div id="result"></div>

Assuming you actually want something like...
<table id="newborn_table">
<tbody>
<tr>
<td>Color</td>
<td>red</td>
</tr>
<tr><!-- etc --></tr>
</tbody>
</table>
You should be able to map your string like so
function createTable(str, id) {
let table = document.createElement('table'),
tbody = document.createElement('tbody');
table.setAttribute('id', id || 'newborn_table');
table.setAttribute('border', 1);
table.appendChild(tbody);
str.split('\n').forEach(row => {
let tr = document.createElement('tr');
row.split(': ').forEach(cell => {
let td = document.createElement('td');
td.textContent = cell;
tr.appendChild(td);
});
tbody.appendChild(tr);
});
return table;
}
var str = `Color: red
Shape: square
Side: 1mm`;
document.body.appendChild(createTable(str));

Related

How to create an array from the columns of a table in Javascript?

I have an HTML table like this:
SALES RENTS
ROME MILAN ROME MILAN MONEY
The HTML code is the following:
<TR>
<TD CLASS=HD1 COLSPAN=2>SALES</TD>
<TD CLASS=HD1 COLSPAN=2>RENTS</TD>
<TD CLASS=HDCOLSEP> </TD>
</TR>
<TR>
<TD>ROME</TD>
<TD>MILAN</TD>
<TD>ROME</TD>
<TD>MILAN</TD>
<TD>MONEY</TD>
</TR>
What I need, is to create with javascript an array like this:
(ROME-SALES, MILAN-SALES, ROME-RENTS, MILAN-RENTS, MONEY).
I have already created the array that contains the element of the first row.
Below you can find my code as it was in the past (At the beginning I needed just to take the elements of the first TR). Now I need to modify it and to create an array as specified before.
I don't know if it is clear from the table, but the first ROME and MILAN columns are referred to the column SALES, the second ROME and MILAN are referred to the RENTS column, while MONEY doesn't have any dependence.
Do you have any idea to do this?
Thanks in advance.
function getColumnsVal(id) {
var header = $("table#" + id + " thead tr:eq(1)");
var header_fields = $("td", header);
var header_vals = [];
header_fields.each(function(idx, val) {
var $$ = $(val);
header_vals.push($$.text());
});
return header_vals;
}
It is definitely possible to read values from the table cells. I edited the post a bit to illustrate the code.
I presume that HTML structure is rigid and you always have two rows of titles in the thead and somewhat random number of merged cells in the first row.
You’d want to match the number of columns in both rows, i.e. take the colspan number into account when traversing the cells.
Read both rows and generate strings by combining cell values in corresponding columns.
For example:
function readTableRow(row) {
var values = [];
$("td", row).each(function(index, field) {
var span = $(field).attr("colspan");
var val = $(field).text();
if (span && span > 1) {
for (var i = 0; i<span; i++ ) {
values.push(val);
}
} else {
values.push(val);
}
});
return values;
}
function getColumnsVal(id) {
// Read the first row, taking colspans into account
var first_row = $("table#" + id + " thead tr:eq(0)");
var first_row_vals = readTableRow(first_row);
// Read the second row, taking colspans into account
var second_row = $("table#" + id + " thead tr:eq(1)");
var second_row_vals = readTableRow(second_row);
if (first_row_vals.length != second_row_vals.length) {
return null;
}
var results = [];
for (var i = 0; i<first_row_vals.length; i++) {
results.push([first_row_vals[i].trim(), second_row_vals[i].trim()].filter(function (el) {return el}).join("-"));
}
return results;
}
function displayResults(results) {
var result = "RESULT: <br />";
results.forEach(function(r) {
result = result + r + "<br />";
});
$("#result").html(result);
}
displayResults(getColumnsVal("sample"));
JSFiddle:
https://jsfiddle.net/adanchenkov/n61dqfrs/

Color specific words (keywords) in a text that is inside a <td>

I'm working im a project and now I need do something that I don't know. I want to color specfic words (keywords) in a text that is inside a <td>
I can do it static, because the texts are random, they come from database.
Its a normal text, I want to color words like "animal, pet", something like this.
And put a specific color for each one, for exemple, animal appers like red, and pet like blue font color.
I think I have to use Jquery do to it, and make a function to do it after the page loads (readyFunction).
But I dont have any ideas to do it, I'm new with jquery. Could you give me some ideas, please ?
Thanks!
This is really "dirty" solution, but will serve you as an example on how to approach your task:
<body>
<table id="the_table">
<tr>
<td>random words from DB: like an apple, pet, whatever, yet another apple</td>
</tr>
</table>
<script>
$(document).ready(function () {
var content_cell,
random_words = "",
colors_map = {
"apple": "red",
"pet": "blue"
};
// selector for your specific table cell
$('#the_table tr').each(function() {
content_cell = $(this).find("td:first");
});
// get cell content
random_words = content_cell.html();
// replace your keywords according the map
$.each(colors_map, function( index, value ) {
random_words = random_words.replace(new RegExp(index, 'g'), "<font color='" + value + "'>" + index + "</font>");
});
// set back html content into the cell
content_cell.html(random_words);
});
</script>
</body>
Suppose your browser support html5, No JQuery is need, try the following code:
function renderKey(){
//create color list in case you don't want to get invisible color such as 'white' from random color..
// make the list long enough to avoid duplicated color
var colors = ['red', 'blue', 'orange', 'cyan', 'black'];
var keyColor = {};
var keyIndex = 0;
//you may need more selectors to exclude unexpected elements, e.g. <td> in <thead>.
var x = document.querySelectorAll("td");
for (i in x){
//suppose your key words seperated by ',' in <td>
var keyWords = x[i].innerHTML.split(',');
x[i].innerHTML = keyWords.reduce(
function(total, value, index){
return total + '<span style="color:' +
(keyColor[value] || (keyColor[value] = colors[ keyIndex++ % colors.length])) +
'">' + value + '</span>';
},
''
);
}
}

Insert javascript code inside Jquery $().append(); [closed]

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 7 years ago.
Improve this question
I have the follow code:
for (var key in returns) {
$('#tBodyTable').append('\
<tr>\
<td >\
<label>'+ returns[key].name +'</label>\
</td>\
<script>\
for (var i in quant_colums){\
document.write("<td ><center><label>a</label></center></td>");\
};\
</script>\
</tr>\
');
};
This code are inside the return of Jquery Ajax, and the first loop overwrite the body the table dynamically. The second loop is for create <td> dynamically based the value of the variable quant_columns, that is why has a javascript there. But I don't know how exactly to do this. Each line of the table will have a number of the columns in determined point, based the result of the query.
How I can do it?
For this case, you do not need to insert a script tag, you can do everything you need in the same function.
$(function(){
var returns = {t1: {name:'teste1'},t2:{name:'teste2'},t3:{name:'teste2'}};
var quant_colums = 3;
var $table = $('#tBodyTable');
for (var key in returns) {
var $tr = '<tr>\
<td >\
<label>'+ returns[key].name +'</label>\
</td>\
</tr>';
for (var i in quant_colums){
$tr.append("<td ><center><label>a</label></center></td>");
}
$table.append($tr);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<table id="tBodyTable"></table>
You can use the DOM to insert elements dynamically based on the data you have like this.
var returns, quant_colums, tbody;
returns = {
a: {name: "a"},
b: {name: "b"},
c: {name: "c"}
};
quant_colums = [0, 1, 2, 3];
tbody = window.document.querySelector("#tBodyTable");
Object.keys(returns).forEach(function (key) {
var row, cell;
row = tbody.insertRow();
cell = row.insertCell();
cell.innerHTML = '<label>' + returns[key].name + '</label>';
quant_colums.forEach(function (i) {
cell = row.insertCell();
cell.innerHTML = "<center><label>" + i + "</label></center>";
});
});
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="script.js"></script>
</head>
<body>
<table>
<tbody id="tBodyTable"></tbody>
</table>
</body>
</html>

Questions about dynamically creating divtags

I'm trying to dynamically create divtags for each cell of my table so that I can later fill them in with other stuff. However, when I tried doing this:
newhtml+="<div id ='" + (j) +"'><td class = 'unselected'>&nbsp?&nbsp</td></div>"
and later using it it acted as if it never created it.
So after browsing stackoverflow I found out that you should use this line of code to dynamically create a div tag:
var divtag = document.createElement('div');
But my question is how do I implement it into my js code?
Here is the section of code that is supposed to create divtags for later referencing:
newhtml+="<tr>";
for (var j = 0; j < $tblcols; j++){
newhtml+="<div id ='" + (j) +"'><td class = 'unselected'>&nbsp?&nbsp</td></div>";
And here is the section that uses it:
divtag = document.getElementById("'" + (++$counter2) + "'");
newhtml +="<td class = 'solved'><img src ='sc2units/" + $counter2 + ".jpg'></td>";
divtag.innerHTML = newhtml;
each section is a nested for loop that goes through the entire array of data that needs outputted.
EDIT: If there is an easier way to fill cells with data in an array I would be happy to know.
I'm not sure on your table, or setup, or exact needs.... But I believe you want to give content to certain table cells after you've already created the cells. You're on to the right idea with naming them, but you can't wrap <td>s in <div>s so your next best option is to simply name the <td>s themselves.
You could also add the content right inside the second loop, but we'll run with this.
HTML
<table id="myTable">
<tr>
<td>[ content ]</td>
</tr>
<tr>
<td>[ content ]</td>
<td>[ content ]</td>
</tr>
[ etc ]
</table>
JavaScript
var tbl = document.getElementById("myTable"),
rows = tbl.getElementsByTagName("tr");
// loop all rows
for (var r = 0; r < rows.length; r++){
// loop all cols within the row
var cols = rows[r].getElementsByTagName("td");
for (var c = 0; c < cols.length; c++){
cols[c].id = "row-" + r + "_col-" + c;
}
}
// usage
document.getElementById("row-1_col-1").innerHTML = "JS POWER";
http://jsfiddle.net/daCrosby/tJYNM/
You can create the elements separately then organize them later, inserting one inside the other. Something like:
var mydiv = document.createElement("DIV");
var mytd = document.createElement("TD");
mytd.innerHTML = "some basic text";
mydiv.appendChild(mytd); // insert the TD inside the DIV
document.body.appendChild(mydiv); // insert the DIV in the document's body
I just don't know what's about putting TD's inside DIV's...

question regarding javascript;Html generation and search current webpage for tags

Hi I have 3 questions, if you have for example this simple website
<html> <head> </head> <body> <table>
<tr> <td>www.hello1.com</td>
</tr> <tr> <td>www.hello2.com</td>
</tr> </table> </html>
Question 1)
If I for instance decide to click on link number 2 (www.hello2.com), Is this stored in some kind of variable?
I know that this is storing the current URL but not the one that you click
window.location.href;
Question 2)
How do you search your document, say that I would like to search the this website and store all the links in a javascript array like this
var myArray = [];
searchThisWebSiteForURLS()//Do this function that I don't know to write that search this htmlsite for url's
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com'];//This is the reslt after that the function has been executed
Question 3)
I would like to write out these links. Say that I have another table like this
<html> <head> </head> <body> <table>
<tr> <td>X</td>
</tr> <tr> <td>Y</td>
</tr> </table> </html>
Where X = http://www.hello1.com
And Y = http://www.hello2.com
Of course it shall be as many rows as there are elements in the array like this
<html> <head> </head> <body> <table>
<tr> <td>X</td></tr>
<tr> <td>Y</td></tr>
<tr> <td>Z</td></tr>
<tr> <td>A</td></tr>
<tr> <td>B</td></tr>
</table> </html>
Where Z, A, B are the elements 3,4,5 in the array
var myArray = [ 'http://www.hello1.com', 'http://www.hello2.com','http://www.hello3.com','http://www.hello4.com','http://www.hello5.com'];
EDIT!--------------------------------------------------------------------------
Wow really thanks, all of you, really thanks! I just have one more question regarding the links, when comparing two links, say that the array looks like this
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.someothersite.at'];
And say that the user has pressed the example "http://www.example.at" link, then I want to create the table containing the similar links. So I do something like this
function checkForSimilarLink(theLinkToCompareWith){// in this case theLinkToCompareWith = "http://www.example.at"
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
//Check if numLinks[i]== theLinkToCompareWith*
}
}
So how would you write this compare function? In this case we can consider
"http://www.example.at" and "http://www.example1.at" the "same" while "http://www.someothersite.at" obviosly aren't
Thanks again :)
I didn't understand question 1, but here's something for question 2 and 3:
Question 2:
var pageLinks = [];
var anchors = document.getElementsByTagName('a');
var numAnchors = anchors.length;
for(var i = 0; i < numAnchors; i++) {
pageLinks.push(anchors[i].href);
}
//now pageLinks holds all your URLs
Question 3:
// say pageLinks holds your desired URLs
var pageLinks = ['http://www.example.at', 'http://www.example2.at', 'http://www.example3.at'];
// create an empty table
var table = document.createElement('table');
// ... and it's tbody
var tbody = document.createElement('tbody');
// loop through your URLs
var numLinks = pageLinks.length;
for(var i = 0; i < numLinks; i++) {
// create new table row...
var tr = document.createElement('tr');
// a cell...
var td = document.createElement('td');
// and your anchor...
var a = document.createElement('a');
// set the anchor's href
a.setAttribute('href', pageLinks[i]);
// set the anchor's text, it's also the URL in this example
a.innerHTML = pageLinks[i];
// append the anchor to the table cell
td.appendChild(a);
// ... and that cell to the new row
tr.appendChild(td);
// ... and that row to the tbody, right? ;-)
tbody.appendChild(tr);
}
// after all rows were added to the tbody,
// append tbody to the table
table.appendChild(tbody);
// and finally append this table to any existing
// element in your document, e.g. the body:
document.body.appendChild(table);
// ...or add it to a div for example:
//document.getElementById('anyDiv').appendChild(table);
Go study JQuery!!!! XDD The best for web development.
for the first and second question in with jquery:
var anchors = $('a'); //returns all <a></a> elements from here you can get the url from all of theam
With jquery u can write any element that you want.
var table = $('<table></table>');
var tr = $('<tr></tr>').appendTo(table);
var td = $('<td></td>').setText('your link here')appendTo(tr);
. . .
table.appendTo(The parent element to add the table);
Question 1:
You can capture the onclick event for clicking on the link and during that store whatever information you want to a variable of your choosing (though, this would only be relevant if you included return false in the onclick event because the link would otherwise take the user to a new page and end your session).
Question 2 and 3 were answered quite well by Alex.

Categories