Parsing HTML plaintext data into javascript array - javascript

So I have a very simple HTML page called Terms.html. Here is the output:
Museums, Parks, Railroads and Trains, Shopping, Theatres
and here is the code:
<!DOCTYPE html>
<html>
<body> Museums, Parks, Railroads and Trains, Shopping, Theatres </body>
</html>
Now, I am using jQuery $.get method to retrieve this html page:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
</head>
<body>
<script>
var tags = [ "String1", "String2"];
$.get("Terms.html", function(data, status) {
<!-- -->
$(result).html( data );
alert("Status: " + status);
});
</script>
<p>Search terms are: <span id="displayterms"></span></p>
<div id="result"><div>
</body>
</html>
What I want to do is be able to parse Museums, Parks, Railroads and Trains, Shopping, Theatres into individual strings and add them to my var tags array. Any ideas on how I can do this? Thanks

Try:
var tags = ["String1", "String2"];
var str = "Museums, Parks, Railroads and Trains, Shopping, Theatres";
arr = $.map( tags.concat(str.split(',')), function( n ) { return $.trim(n) });
console.log(arr); // Outputs the array ["String1", "String2", "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
jsFiddle example
The third line splits the str on the commas and then uses jQuery's .map() function to trim the whitespace.

With the split function: http://www.w3schools.com/jsref/jsref_split.asp
This will split on any character you choose, in this case ","
tags = data.split(",");

If you don't need to support versions of IE older than 9, you could do something like this:
var tags = document.body.textContent.split(',').map(
function (s) {
return s.trim();
}
);
document.body.textContent gets the text in the body tag. This restricts your browser support, as IE didn't have this until version 9.
.split(',') takes the string and splits it into its component parts, returning an array.
.map() applies a function to everything in the array returned by .split(','), and returns an array of the results. In this case, we use it to call trim() on each string in the array, to strip leading and trailing whitespace. IE didn't have the Array.prototype.map or String.prototype.trim methods until version 9, but they're easy to polyfill. It's the textContent thing above that's trickier.
The array returned from map() is then put into your tags variable.

Instead of storing the contents as HTML, you could store them in a JSON data file.
An example JSON data file (places.json):
{
"Names": [ "Museums", "Parks", "Railroads and Trains", "Shopping", "Theatres"]
}
Then, you can change your page code to:
<script>
var tags = [ "String1", "String2"];
$.getJSON("/places.json", function(data) {
$(result).html(data);
console.log(data.Names[0]); // Outputs Museums
$.each(data.Names, function(index, value) {
tags.push(value); // add the tag to your tags list for each item in Names
});
});
</script>
This way you can store just the data you need and you won't need to parse the HTML manually.

Related

Function output of JavaScript function not showing in html

The Javascript code is working but I don't know how I can make it work in HTML. I want to link it to an external Javascript file.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
console.log(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
HTML code:
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
I believe you want to print or display the output of that function on the web page.
If that's the case. There are various ways to accomplish this.
Before I go any further, I'd want to point out that you are, in fact, printing something, which is what you intended for your function.
But you can't see it since it's printed in the console.
You may view this by using the F12 key after loading your website.
The console will then appear, and the needed output will be printed.
And here's one method for displaying your output in an HTML page.
You just have to replace your console.log() with the document.write().
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
document.write(find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']))
<!DOCTYPE html>
<html>
<body>
<script src="findLongestWord.js"></script>
</body>
</html>
Here is another method to achieve this.
You can add an html element and change the content of that particular element by using document.getElementById("id name of the element").innerHTML.
Here is the code snippet.
function find_longest_string(input_array) {
var large = input_array[0].length; //storing the length of each word in the variable large
input_array.map(var_new => large = Math.max(large, var_new.length)); //used map to check the largest word
answer = input_array.filter(var_new => var_new.length == large); //storing the words which are larger
return answer[0]; //displaying the first largest word
}
const largest_word = find_longest_string(['mystery', 'brother', 'aviator','crocodile','pearl','orchard','crackpott']);
document.getElementById("demo").innerHTML =largest_word
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script src="findLongestWord.js"></script>
</body>
</html>

Adding html table to javascript using document.write

Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.

Parse content from a html page

Need to dynamically update contents in a div of main page, based on data fetched from other html page
setInterval( function() {
$.ajax({
type:'GET',
url:"url for status",
success : function(data){
console.log(data);
}
})
},3000);
The content of 'data' printed in developer tool console is:
<html>
<style>
</style>
<head>
</head>
<script>
var conns=[{num:1,
id:1,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_1',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
},
{num:2,
id:2,
Conn:[{type:'ppp',
Enable:1,
ConnectionStatus:'Disconnected',
Name:'CONNECTION_2',
Uptime:0,
ConnectionError:'TIME_OUT',
..............
}]
}]
</script>
</html>
Need to extract the ConnectionStatus, Name and ConnectionError from this content and display it in respective div in main page.
I would recommend using a different transfer type, however, you could use something like this:
function break_out_each_id(){//returns array of indexes where id starts
var i = 0;
id_objs = [];
while data.indexOf('id', i) > -1{
id_objs[i] = data.indexOf('id', i);
i++;
}
return id_objs
}
function find_values(){//pseudo code
use the array of indexes from first index to next index
in that string, do index of each value you are looking for (ConnectionStatus...)
then parse that line after the ':' to get the value.
Do this for each index in indexes array
}
Sorry for the pseudo code, but this post is getting really long. Like I said, it would be MUCH better to just send the response as JSON (even if it is a stringified version of it). In that case you could just do a simple JSON.parse() and you'd be done.

Error while parsing JSON string using JQuery

I am trying to read values from JSON string and display some of it's values using JavaScript alert() statement. But I am getting following exception in the console.
Please guide.
Console Exception
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
...dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){...
at jquery.min.js(line 4, col 5304)
process.js
$(document).ready(function () {
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
console.log(json);
$.each($.parseJSON(json), function (idx, obj) {
alert(obj.name);
});
});
home.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='${studentsJson}'></div>
</body>
</html>
View Page Source of home.jsp
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="js/process.js"></script>
</head>
<body>
From JQuery (JSON): <div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
</body>
</html>
Since jQuery 1.6 the .data() method parses the values, so remove the $.parseJSON(). You are parsing the object not string that causing the error here. Also check - Why is jQuery automatically parsing my data-* attributes?
Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.
When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string. ( Taken from https://api.jquery.com/data/ )
$(document).ready(function() {
//static message
var msg = "Hello World from JQuery!";
$("#mydiv").text(msg);
//dynamic message processing for displaying value in div element
var students = $("#studentDiv").data("students");
$("#studentDiv").text(students);
//for handling json data
var json = $("#studentJsonDiv").data("students-json");
// change value here ---------------^------^------
console.log(json);
$.each(json, function(idx, obj) {
alert(obj.name);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
From JQuery:
<div id="studentDiv" data-students="[Student{id=1, name=Jack}, Student{id=2, name=Jill}]"></div>
From JQuery (JSON):
<div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
The data you get is an Array of objects. You just have to iterate over it, without having to parse it again. Also, correct attribute name.
var json = $("#studentJsonDiv").data("students-json");
$.each(json, function (idx, obj) {
alert(obj.name);
});
You need to use students-json in data because that is where you have your json data
var json = $("#studentJsonDiv").data("students-json");
$.each($.parseJSON(json), function(idx, obj) {
alert(obj.name);
});
If you're parsing
[Student{id=1, name=Jack}, Student{id=2, name=Jill}]
it's missing : after Student.

How to display a list of JSON objects onto html page

NOTE: Need to implement this without the use of jQuery or any other open source code.
Here is what I have
HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Model</title>
<script src="js.js"></script>
</head>
<body>
<h1>Browse all our products below:</h1>
Name: <span id="name"></span><br>
Desc: <span id="desc"></span><br>
Cost: <span id="cost"></span><br>
Stock: <span id="stock"></span>
</body>
</html>
js.js is below
var getProducts = function(){
console.log("Getting Products...");
var success = function() {
var product = JSON.parse(xhr.responseText);
console.log(product);
document.getElementById("name").innerHTML = product.name;
document.getElementById("desc").innerHTML = product.desc;
document.getElementById("cost").innerHTML = product.cost;
document.getElementById("stock").innerHTML = product.stock;
}
};
xhr = new XMLHttpRequest();
xhr.open("GET", "back.php");
xhr.addEventListener("load", success);
xhr.send();
};
window.addEventListener("load", getProducts);
back.php returns the following from a database. They have been json_encoded:
{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"}
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"}
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"}
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"}
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}
I need to display these objects onto the html page. I know I need to implement a for loop however, no matter whatever I try, a parse error for JSON comes up.
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at
line 1 column 86 of the JSON data
var product = JSON.parse(xhr.responseText);
Would much appreciate it if someone could help me understand how to display all the JSON objects onto the html page.
Your JSON is invalid. You need to put the objects in an array, and separate them by commas.
[{"name":"TESTPRODUCT","desc":"TESTIN12356879CEWBLABHDSB","cost":"123.45","stock":"6"},
{"name":"soot","desc":"soooottty black","cost":"980.00","stock":"10"},
{"name":"baby","desc":"chucky doll","cost":"7.92","stock":"34"},
{"name":"bob","desc":"fydrtsfxgcvnb","cost":"3546.00","stock":"978"},
{"name":"bolly","desc":"ball","cost":"77.00","stock":"89"}]
Here is an example using open source project jinqJs
Also the example is using jQuery.
Fiddle Example
//data can also be a string to a url that returns JSON
jinqJs().from(data).select(function(row) {
$('#items')
.append($("<option></option>")
.attr("value",row.nam)
.text(row.desc));
}
);

Categories

Resources