How to write an array object/element to a table in Javascript - javascript

My title for this question may not be using the correct terminology but here is what I would like to do. (I am still new to Javascript so im looking for a basic method)
First my table has to be created using Javascript,
then I need to take an array object/element and "write" it to a table cell.
I say "write" because I'm not sure if that's the correct word to use.
Here is an example of the code I'm working with:
<script type="text/javascript">
/* <![CDATA[ */
var day = [];
day[0] = "monday"
document.write("<table>")
document.write("<tr><td>"**what syntax do i use to insert the data for "day[0]" here**"</td></tr>")
document.write("</table>")
/* ]]> */
</script>

try
<script type="text/javascript">
/* <![CDATA[ */
var day = [];
day[0] = "monday";
document.write("<table>")
document.write("<tr><td>" + day[0] + "</td></tr>")
document.write("</table>")
/* ]]> */
</script>
also you don't have to declare the array like
var day = [];
day[0] = "monday";
you can simply do
var day = ["monday"];

Related

Define Values to label using javascript on blogger

I am trying to use the label to display values in a list.
For example: apple, 500kg, $3000 using these label I will display in a list.
to retrieve labels in javascript I used:
<script type="text/javascript">
function listEE(json) {
var ListTagEE= "";
for (var k = 0; k < json.feed.category.length; k++)
{
ListTagEE += ""+json.feed.category[k].term+""; }
var listing = ""
+ListTagEE+
"" ;
document.write(listing);
}
</script>
<!-- ######### Invoking the Callback Function ############# -->
<script type="text/javascript" src='https://someadresss.blogspot.com/feeds/posts/default?alt=json-in-script&callback=listEE'>
</script>
And this is code I used to replace labels with my specific values.
<script>
function lebel23_logo(etiqueta23) {
ratstok = new Array();
ratstok[1] = "Apple Peter"
ratstok[2] = "Mango"
ratstok[3] = "Pine Apple"
if (etiqueta23 == "Apple") {document.write(ratstok[1]);}
if (etiqueta23 == "Mango") {document.write(ratstok[2]);}
if (etiqueta23 == "Pineapp") {document.write(ratstok[3]);}
}</script>
earlier I was using blogger < b: loop> label tag to retrieve label. and used following code.. to display the output
lebel23_logo("<data:label.name/>");
Now I am retrieving labels in javascript through above code which is working. but not able to change label and display it with above function lebel23_logo.
Uncaught TypeError: lebel23_logo is not a function on line 9
https://js.do/helloaaa/asasqqq
sorry, my English and javascript is not that good. i hope I made this post understandable.
Replace ""+json.feed.category[k].term+"" with +lebel23_logo(json.feed.category[k].term)+
https://js.do/MustaphaBouh/asasqqq

Randomly redirect to url BUT 1 number changes (via Javascript)

So, I use this code
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = urls[random];
</script>
and I use "/truth1" "/truth2" "dare1" etc
Is it at all possible to have javascript automatically put a random number at the end of the URL between what I set it to?
In other words
I want Javascript to add a number to the end of
truthordare0.weebly.com/truth
truthordare0.weebly.com/dare
To truthordare0.weebly.com/dare1, truthordare0.weebly.com/dare2
To truthordare0.weebly.com/truth1, truthordare0.weebly.com/truth2
putting a random number between 1-25 at the end of "truth" or "dare". If I have to make the numbers two-digit, please let me know!
It might be handy to know:
-The code above will be used on truthordare0.weebly.com/truth
(which will redirect to /truth1, /truth2, etc
-The code above is used in vitemulti.weebly.com/yesorno-select
Thank you very much!!
<script type="text/javascript">
var urls = new Array();
urls[0] = "/truth";
urls[1] = "/truth1";
urls[2] = "truth2";
var random = Math.floor(Math.random()*urls.length);
window.location = "https://truthordare0.weebly.com/" + urls[random];
</script>

Replace / Ignore JavaScript in a String

I wrote a small RSS reader with JQuery. At first theres a screen with the titles of the articles, when clicked on a title I load the content of that article. The problem is, it contains some google ads script, which will replace the content of the article and fill the whole screen with an advertisement.
The following script is what I am tying to replace or ignore:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-8356817984200457";
/* ijsselmondenieuws.nl */
google_ad_slot = "9061178822";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script><br />
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
So I wrote a method which is supposed to remove the script by a simple replace:
var replaceScript='<script type="text/javascript"><!--\n' +
'google_ad_client = "ca-pub-8356817984200457";\n' +
'/* ijsselmondenieuws.nl */\n' +
'google_ad_slot = "9061178822";\n' +
'google_ad_width = 468;\n' +
'google_ad_height = 60;\n' +
'//-->\n' +
'</script>\n' +
'<script type="text/javascript"\n' +
'src="http://pagead2.googlesyndication.com/pagead/show_ads.js">\n' +
'</script>';
function removeADS(ads) {
removeAD = ads.replace(replaceScript, " ");
}
But this doesn't work, I think it's not flexible either (if it would work). When something changes in the script, the application will get stuck at the advertisement again. Is there some way to completely ignore this script while fetching the content from an RSS feed or a more flexible replacement script?
Any help is appreciated,
Thanks!
It's not very wise to parse xml/html with regex.
Use a dom parser (jquery is a beautiful one ...hint hint):
var rssContentString = '<rss version='2.0'>...',
xmlDoc = $.parseXml(rssContentString),
$xml = $(xmlDoc),
helper = $('<div />'),
result;
result = helper
.append(
$xml
.find('script')
.remove()
.end()
)
.text();
UPDATE
Based on the new comments, since you get your rss content like this :
content:$.trim($(v).find("content").text())
you can modify this expression to the following :
content:$.trim($(v).find("content").find('script').remove().end().text())

Unable to retrieve values from eBay API response using Javascript

I am trying to build a very simple tool for use at my work. I work for eBay and currently the tools available are cumbersome for the task. We are asked to compare text and images to check that sellers aren't stealing each others content. I am using the eBay Trading API and the sample HTML/CSS/Javascript code given when the developer account was created. Ultimately what I hope to achieve is a simple page that displays two items' photo and description next to each other. However, right now I am simply trying to edit the sample code given to display the start date of the auction.
My question is this: I am trying add a variable who's value is determined by a response from the API. some of these are provided in the sample however, when I add my own var starttime = items.listingInfo.startTime to the function and add the variable to the HTML table none of the data displays including those that displayed prior to my addition. Unfortunately I don't have more than a rudimentary understanding of javascript and so am unsure if I am even properly phrasing this question, let alone getting the syntax of my addition correct. What am I doing wrong?
below is the sample text with my addition of one declared variable (starttime) and one addition to the HTML table
<html>
<head>
<title>eBay Search Results</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
</head>
<body>
<h1>eBay Search Results</h1>
<div id="results"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = items.listingInfo.startTime;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '' + starttime + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%203g&paginationInput.entriesPerPage=3>
</script>
</body>
</html>"
If you believe listingInfo is an property of individual items, and that it is an object that has the property startTime, then the proper syntax is:
var item = items[i];
var title = item.title;
var viewitem = item.viewItemURL;
var starttime = item.listingInfo.startTime;
You are currently referencing items which is the array of items, not an individual item.
Update
I looked into this via the URL you put in the comments. The solution to this particular problem is this:
var starttime = item.listingInfo[0].startTime;
I hope that helps. Please review the FAQ; Imho this question falls outside the scope of this site (the question is really quite narrow, and not likely to help anyone else). I recommend Mozilla Developer Network as a source for learning more about JavaScript.

Best way to parse HTML in Javascript

I am having a lot of trouble learning RegExp and coming up with a good algorithm to do this. I have this string of HTML that I need to parse. Note that when I am parsing it, it is still a string object and not yet HTML on the browser as I need to parse it before it gets there. The HTML looks like this:
<html>
<head>
<title>Geoserver GetFeatureInfo output</title>
</head>
<style type="text/css">
table.featureInfo, table.featureInfo td, table.featureInfo th {
border:1px solid #ddd;
border-collapse:collapse;
margin:0;
padding:0;
font-size: 90%;
padding:.2em .1em;
}
table.featureInfo th {
padding:.2em .2em;
font-weight:bold;
background:#eee;
}
table.featureInfo td{
background:#fff;
}
table.featureInfo tr.odd td{
background:#eee;
}
table.featureInfo caption{
text-align:left;
font-size:100%;
font-weight:bold;
text-transform:uppercase;
padding:.2em .2em;
}
</style>
<body>
<table class="featureInfo2">
<tr>
<th class="dataLayer" colspan="5">Tibetan Villages</th>
</tr>
<!-- EOF Data Layer -->
<tr class="dataHeaders">
<th>ID</th>
<th>Latitude</th>
<th>Longitude</th>
<th>Place Name</th>
<th>English Translation</th>
</tr>
<!-- EOF Data Headers -->
<!-- Data -->
<tr>
<!-- Feature Info Data -->
<td>3394</td>
<td>29.1</td>
<td>93.15</td>
<td>བསྡམས་གྲོང་ཚོ།</td>
<td>Dam Drongtso </td>
</tr>
<!-- EOF Feature Info Data -->
<!-- End Data -->
</table>
<br/>
</body>
</html>
and I need to get it like this:
3394,
29.1,
93.15,
བསྡམས་གྲོང་ཚོ།,
Dam Drongtso
Basically an array...even better if it matches according to its field headers and from which table they are somehow, which look like this:
Tibetan Villages
ID
Latitude
Longitude
Place Name
English Translation
Finding out JavaScript does not support wonderful mapping was a bummer and I have what I want working already. However it is VERY VERY hard coded and I'm thinking I should probably use RegExp to handle this better. Unfortunately I am having a real tough time :(. Here is my function to parse my string (very ugly IMO):
function parseHTML(html){
//Getting the layer name
alert(html);
//Lousy attempt at RegExp
var somestring = html.replace('/m//\<html\>+\<body\>//m/',' ');
alert(somestring);
var startPos = html.indexOf('<th class="dataLayer" colspan="5">');
var length = ('<th class="dataLayer" colspan="5">').length;
var endPos = html.indexOf('</th></tr><!-- EOF Data Layer -->');
var dataLayer = html.substring(startPos + length, endPos);
//Getting the data headers
startPos = html.indexOf('<tr class="dataHeaders">');
length = ('<tr class="dataHeaders">').length;
endPos = html.indexOf('</tr><!-- EOF Data Headers -->');
var newString = html.substring(startPos + length, endPos);
newString = newString.replace(/<th>/g, '');
newString = newString.substring(0, newString.lastIndexOf('</th>'));
var featureInfoHeaders = new Array();
featureInfoHeaders = newString.split('</th>');
//Getting the data
startPos = html.indexOf('<!-- Data -->');
length = ('<!-- Data -->').length;
endPos = html.indexOf('<!-- End Data -->');
newString = html.substring(startPos + length, endPos);
newString = newString.substring(0, newString.lastIndexOf('</tr><!-- EOF Feature Info Data -->'));
var featureInfoData = new Array();
featureInfoData = newString.split('</tr><!-- EOF Feature Info Data -->');
for(var s = 0; s < featureInfoData.length; s++){
startPos = featureInfoData[s].indexOf('<!-- Feature Info Data -->');
length = ('<!-- Feature Info Data -->').length;
endPos = featureInfoData[s].lastIndexOf('</td>');
featureInfoData[s] = featureInfoData[s].substring(startPos + length, endPos);
featureInfoData[s] = featureInfoData[s].replace(/<td>/g, '');
featureInfoData[s] = featureInfoData[s].split('</td>');
}//end for
alert(featureInfoData);
//Put all the feature info in one array
var featureInfo = new Array();
var len = featureInfoData.length;
for(var j = 0; j < len; j++){
featureInfo[j] = new Object();
featureInfo[j].id = featureInfoData[j][0];
featureInfo[j].latitude = featureInfoData[j][1];
featureInfo[j].longitude = featureInfoData[j][2];
featureInfo[j].placeName = featureInfoData[j][3];
featureInfo[j].translation = featureInfoData[j][4];
}//end for
//This can be ignored for now...
var string = redesignHTML(featureInfoHeaders, featureInfo);
return string;
}//end parseHTML
So as you can see if the content in that string ever changes, my code will be horribly broken. I want to avoid that as much as possible and try to write better code. I appreciate all the help and advice you can give me.
Do the following steps:
Create a new documentFragment
Put your HTML string in it
Use selectors to get what you want
Why do all the parsing work - which won't work anyways, since HTML is not parsable via RegExp - when you have the best HTML parser available? (the Browser)
You can use jQuery to easily traverse the DOM and create an object with the structure automatically.
var $dom = $('<html>').html(the_html_string_variable_goes_here);
var featureInfo = {};
$('table:has(.dataLayer)', $dom).each(function(){
var $tbl = $(this);
var section = $tbl.find('.dataLayer').text();
var obj = [];
var $structure = $tbl.find('.dataHeaders');
var structure = $structure.find('th').map(function(){return $(this).text().toLowerCase();});
var $datarows= $structure.nextAll('tr');
$datarows.each(function(i){
obj[i] = {};
$(this).find('td').each(function(index,element){
obj[i][structure[index]] = $(element).text();
});
});
featureInfo[section] = obj;
});
Working Demo
The code can work with multiple tables with different structures inside.. and also multiple data rows inside each table..
The featureInfo will hold the final structure and data, and can be accessed like
alert( featureInfo['Tibetan Villages'][0]['English Translation'] );
or
alert( featureInfo['Tibetan Villages'][0].id );
The "correct" way to do it is with DOMParser. Do it like this:
var parsed=new DOMParser.parseFromString(htmlString,'text/html');
Or, if you're worried about browser compatibility, use the polyfill on the MDN documentation:
/*
* DOMParser HTML extension
* 2012-09-04
*
* By Eli Grey, http://eligrey.com
* Public domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/*! #source https://gist.github.com/1129031 */
/*global document, DOMParser*/
(function(DOMParser) {
"use strict";
var
DOMParser_proto = DOMParser.prototype
, real_parseFromString = DOMParser_proto.parseFromString
;
// Firefox/Opera/IE throw errors on unsupported types
try {
// WebKit returns null on unsupported types
if ((new DOMParser).parseFromString("", "text/html")) {
// text/html parsing is natively supported
return;
}
} catch (ex) {}
DOMParser_proto.parseFromString = function(markup, type) {
if (/^\s*text\/html\s*(?:;|$)/i.test(type)) {
var
doc = document.implementation.createHTMLDocument("")
;
if (markup.toLowerCase().indexOf('<!doctype') > -1) {
doc.documentElement.innerHTML = markup;
}
else {
doc.body.innerHTML = markup;
}
return doc;
} else {
return real_parseFromString.apply(this, arguments);
}
};
}(DOMParser));
Change server-side code if you can (add JSON)
If you're the one that generates the resulting HTML on the server side you could as well generate a JSON there and pass it inside the HTML with the content. You wouldn't have to parse anything on the client side and all data would be immediately available to your client scripts.
You could easily put JSON in table element as a data attribute value:
<table class="featureInfo2" data-json="{ID:3394, Latitude:29.1, Longitude:93.15, PlaceName:'བསྡམས་གྲོང་ཚོ།', Translation:'Dam Drongtso'}">
...
</table>
Or you could add data attributes to TDs that contain data and parse only those using jQuery selectors and generating Javascript object out of them. No need for RegExp parsing.
Use John Resig's* pure javascript html parser
See demo here
*John Resig is the creator of jQuery
I had a similar requirement and not being that experienced with JavaScript I let jquery handle it for me with parseHTML and using find. In my case I was looking for divs with a particular class name.
function findElementsInHtmlString(document, htmlString, query) {
var domArray = $.parseHTML(htmlString, document),
dom = $();
// create the dom collection from the array
$.each(domArray, function(i, o) {
dom = dom.add(o);
}
// return a collection of elements that match the query
return dom.find(query);
}
var elementsWithClassBuild = findElementsInHtmlString(document, htmlString, '.build');

Categories