Text to Html list - javascript

I want to make a html which will auto get the information for a *.txt file
something1
something2
something3
and output into this html file
<!DOCTYPE html>
<html>
<head>
<title>List</title>
</head>
<body>
<ul>
#here to output#
</ul>
</body>
</html>
I prefer to use JavaScript. Some help is appreciated.

You have to request the file using AJAX call. Then you need to iterate through each line of response and generate DOM element (li in this case) and input line inside of it. After that insert each li element into your ul list.
You can achieve it using jQuery as you are probably new to JavaScript it's probably the easiest way.
What you need to do is request the file first:
$.ajax('url/to/your/file', {
success: fileRetrieved
});
Now after the file is retrieved jQuery will call fileRetrieved method, so we have to create it:
function fileRetrieved(contents) {
var lines = contents.split('\n');
for(var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
Now for each line from the file function fileRetrieved will call createListElement function passing line of text to it. Now we just need to generate the list element and inject it into DOM.
function createListElement(text) {
var into = $('ul');
var el = $('<li></li>').html(text);
el.appendTo(into);
}
Of course you don't want to retrieve into element each time createListElement is called so just store it somewhere outside the function, it's your call, I'm just giving you the general idea.
Here is an example of the script (without AJAX call of course as we can't simulate it):
var into = $('#result');
function fileRetrieved(contents) {
var lines = contents.split('\n');
for (var i = 0; i < lines.length; i += 1) {
createListElement(lines[i]);
}
}
function createListElement(text) {
var el = $('<li></li>').html(text);
el.appendTo(into);
}
var text = $('#text').html();
fileRetrieved(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- This element simulates file contents-->
<pre id="text">
fdsafdsafdsa
fdsafd
safdsaf
dsafdsaf
dsafdsafds
afdsa
</pre>
<div id="result"></div>

Try this
<html>
<head>
<title>List</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<ul id="renderTxt_list">
</ul>
<input type="button" id="lesen" value="Read Data" />
</body>
<script>
$(document).ready(function(){
$("#lesen").click(function() {
$.ajax({
url : "testTxt.txt",
dataType: "text",
success : function (data) {
$html = "";
var lines = data.split("\n");
for (var i = 0, len = lines.length; i < len; i++) {
$html += '<li>'+lines[i]+'</li>';
}
$("body ul").append($html);
}
});
});
});
</script>
</html>

You need to request the file first, and then append it to your chosen place in the document.
You can for example use jQuery's get (or any other function like the native fetch), and then inject it into the ul element:
$.get("*.txt").then(x => $("ul").html("<li>" + x.split('\n').join('</li><li>') + "</li>"))
Let's break this solution by steps:
First, we need to request the external file:
$.get("*.txt")
Read about jQuery's get here. Basicly it will request the file you asked for using network request, and return a promise.
In the Promise's then, we can do stuff with the request's result after it is resolved. In our case we want to first break it by lines:
x.split('\n')
split will return an array that will look like this: ["line 1, "line 2", "line 3"].
JS arrays have the join method, which concat them to string while putting the string you want between the items. So after we do this:
x.split('\n').join('</li><li>')
We only need to add the <li> element to the start and end of the string like this:
"<li>" + x.split('\n').join('</li><li>') + "</li>"
Finally we appent it to your chosen element using jQuery's html.

Related

HTML href as Google Apps Script variable

i'm making an index that generates automatically from a Google Spreadsheet.
My script reads two columns, one with names and the other one with links. Then it generates an HTML with all the names as <li><a>"The name"</a></li>.
My idea is to pass the links on the spreadsheet to the href=" " on each name, but I don't know how to do it.
Here is my .gs and .html code, and a link to my spreadsheet (to work on it, you may have to make a copy).
https://docs.google.com/spreadsheets/d/1fEYqPnp9SIS7I2lzeeoEP7Pui4l0dgLD6t7D9Lki9oE/edit?usp=sharing
GS code
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Index');
function readData() {
var range = spreadsheet.getRange(1, 1,spreadsheet.getLastRow(), spreadsheet.getLastColumn()).getValues();
Logger.log(range);
return range;
};
function readLinks() {
var links = spreadsheet.getRange(1, 2,spreadsheet.getLastRow(), spreadsheet.getLastColumn()).getValues();
Logger.log(links);
return links;
};
HTML code
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div>
<ul>
<li id="proced"><a id="link"></a></li>
</ul>
</div>
<script>
function getData(values) {
values.forEach(function(item, index) {
var x = document.getElementById("link");
x.innerHTML += '<li>' + item[0] + '</li>';
});
}
google.script.run.withSuccessHandler(getData).readData();
</script>
</body>
</html>
Below is the modified code
GS code
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Index');
function readData() {
var data = spreadsheet.getDataRange().getValues()
Logger.log(data)
return data
}
HTML code
<script>
function getData(values) {
var x = document.getElementById("link");
values.forEach(function(item) {
x.innerHTML += '<li>' + item[0] + '</li>';
});
}
google.script.run.withSuccessHandler(getData).readData();
</script>
Changes
Here are the main changes I made:
.gs
Instead of getting the Names and Links separately, now the function readData gets the corresponding names and links all together by using getDataRange.
This returns a two dimensional array like this:
[
["Google", "http://www.google.com/"],
["Facebook", "http://www.facebook.com/"],
["Twitter", "http://www.twitter.com/"],
["Youtube", "https://www.youtube.com"],
["Instagram", "http://www.instagram.com/"],
["Reddit", "http://www.reddit.com/"],
["Bing", "http://www.bing.com/"],
]
This makes the script faster, but if you want to get the ranges individually then you would need to use getRange("A1:A7") or with your method of getting last rows etc. Then get both ranges. The best thing would be to put them together into a two-dimensional array to pass them to the HTML together, if not it complicates things too much, because you will need to construct a chain of call backs to get the names and then wait for the links and then link them up together on the client-side anyway.
.html
Moved var x = document.getElementById("link"); outside the forEach loop. This stays the same for each item so no need to reinitialize it each time.
Changed forEach arguments to function(item) as you don't use the index.
Since each item is now a one-dimensional array eg => ["Google", "http://www.google.com/"] you can call:
item[0] => "Google"
item[1] => "http://www.google.com/"
So the resulting forEach is:
values.forEach(function(item) {
x.innerHTML += '<li>' + item[0] + '</li>';
});

Can't append table to div

I created a table using d3.js library,
but when I try to append the table to a div, it gives an error?
code:
<head>
<script src="../../d3.min.js"></script>
</head>
<body>
<div id="main">
Hi
</div>
<script>
const table = d3.create("table");
const tbody = table.append("tbody");
var i,j,row;
for(i=0;i<5;i++){
row =tbody.append("tr");
for(j=0;j<3;j++){
row.append("td").text(`${i},${j}`);
}
}
console.log(typeof(table));
console.log(table);
node =table.node();
console.log(typeof(node));
console.log(node);
d3.select("#main").append(node);
</script>
</body>
</html>
but I get an error:
although my code similar to what is in this tutorial
A tutorial on d3js
Observable tutorials are meant to create Observable notebooks. There are several small differences between Observable and a regular D3 running in a browser.
That being said, the only problem in your approach is that append requires either a string with the tag name or the element. If you have a string, just use it as append("foo"). However, if you have the element to be appended (in your case, table.node()), you have to return it from a function.
So, instead of:
d3.select("#main").append(node);
It has to be:
d3.select("#main").append(() => node);
Here is your code with that change only:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="main">
Hi
</div>
<script>
const table = d3.create("table");
const tbody = table.append("tbody");
var i, j, row;
for (i = 0; i < 5; i++) {
row = tbody.append("tr");
for (j = 0; j < 3; j++) {
row.append("td").text(`${i},${j}`);
}
}
node = table.node();
d3.select("#main").append(() => node);
</script>
Finally, if you are writing regular scripts for a browser, just ditch this d3.create() followed by append(() => selection.node()). Use a simple tag string instead.

How to append Ajax Json respond to html?

I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

HTML with XML using jQuery

i have xml file which contains lots of data. now i want to pick a price with some condition. i set a parameteres in javascript function but it is not giving desire result. i think it can be done through childnode but i didnot aware about that
XML file
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="PER" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
<flights updated="2012-03-09T04:38:00.437" type="flights" ob_id="45792117" lastedit="2012-03-09T15:10:01" partner_id="63" activate_date="2012-02-15T00:00:00" page_id="9646" page_pk_id="12597" pos_pk_id="51565" pos="1" module_id="3" pos_name="Flights" product_type_id="4" product_type="flight" headline="Bali" destination="Bali" localised_destination="Denpasar" headline_no_html="Bali" price="199" deals_space_limited="0" deals_sold_out="0" qa_approved="1" tp_available="0" tp_weight="10" partner_eapid="0-25" partner_pid="25" publish_path="\\dubvappdaily01\daily_aus\data\psf\" partner_lang_id="3081" FrTLAs="SYD" ToTLAs="DPS" FrDate="2012-04-27T00:00:00" ToDate="2012-05-04T00:00:00" Airline="QZ"/>
HTML page
<head>
<script type="text/javascript">
function myXml(origin, destination ) {
var x = xmlDoc.getElementsByTagName("flights");
for(i=0; i<x.length; i++) {
if (x[i].getAttribute('FrTLAs') == origin
&& x[i].getAttribute('destination') == destination) {
alert(x[i].getAttribute('price'))
}
}
}
</script>
</head>
<body>
click me
</body>
did u miss this??
xmlDoc=loadXMLDoc("flights.xml");
chk this page
http://www.w3schools.com/dom/prop_element_attributes.asp
the example2 is very clear how to use this
x=xmlDoc.getElementsByTagName("book")[0].attributes;
//here its would be getElementsByTagName("flights") in the loop
//then .attributes on it
// and then this
frtlas=x.getNamedItem("FrTLAs");
desti=x.getNamedItem("destination");
//and your code here
hope this helps

Categories

Resources