This is my entrance into programming, I have been working with JS for
two weeks for school. The project is to build a website for a rug
shop.
This week's assignment is writing a table and populating the fields
using arrays accessed by for loop. The arrays have to be stored in
separate JS page, and functions are in the actual HTML page.
Here are my arrays on its own js page:
function getID()
{
var url = window.location.toString();
var i = 0;
if(url.indexOf("?id=")>0)
{
var start = url.lastIndexOf("?id=")+ 4;
i = url.substring(start);
}
return i;
}
//array containing names of individual rugs in inventory
var aName = new Array();
aName[0] = "Red/Blue3x5";
aName[1] = "Blue/Yellow5x8";
aName[2] = "VintagePersian7x10";
aName[3] = "Oversize.20x20";
//array containing prices on rug inventory
var aPrice = new Array();
aPrice[0] = "$299.00";
aPrice[1] = "$700.00";
aPrice[2] = "$2,999.00";
aPrice[3] = "$25,000.00";
//array containing images individual rugs in inventory
var aImage = Array();
aImage[0] = src="red.blue.3x5.jpg";
aImage[1] = src="blue.yellow.5x8.jpg";
aImage[2] = src="vintage.persian.7x10.jpg";
aImage[3] = src="oversize.20x20.jpg";
Here's the segment of HTML page table where the images should appear
in the first column :
<tbody>
<script type="text/javascript">
//tabel header
document.write("<table border='1' rules='rows' cellspacing='0'>");
document.write("<tr>");
document.write("<th> </th><th>Name</th><th>Price</th><th>Order</th>");
document.write("</tr>");
//loop through aName aray & write results
for (var i =0; i < aName.length ; i++) {
document.write("<tr>");
//initialize empty array
var pictures = [];
//insert place holder
var image = new Image;
//set src attribute
image.src = 'images/' + aImage[i];
pictures.push(image);
document.write("<td>");
document.write("<image src='aImage[i]' width='50' height='20'" + " />");
document.write("</td>");
document.write("<td>" + aName[i] + "</td>");
document.write("<td>" + aPrice[i] + "</td>");
//to create hyperlinks for products
document.write("<td><span class='link'><a href='#' title='price'>price</a></span>");
}
</script>
</tbody>
The table appears with the proper columns, but the place where the
image should appear displays a blank spot, and debugging shows:
"Failed
to load resource: net::ERR_FILE_NOT_FOUND" message.
i cleaned this up a bit and fixed the <img> for you.
i added comments to the code to help you. let me know if you need anything else. please see the notes below for more information about my suggested changes. good luck!
i don't think you need to instantiate new Image objects when
you're writing the <img> tags to the DOM.
i named the external script data.js and i included it with a
<script> tag within the <html> tag.
you need to make sure that the images are saved in a directory
called images on the same level and in the same directory as the
html file. others have mentioned this above. let us know if you need more clarification.
// this is "data.js"
function getID () {
var url = window.location.toString();
var i = 0;
if (url.indexOf("?=") > 0) {
var start = url.lastIndexOf("?id=") + 4;
i = url.substring(start);
}
return i;
}
var aName = [];
aName[0] = "Red/Blue3x5";
aName[1] = "Blue/Yellow5x8";
aName[2] = "VintagePersian7x10";
aName[3] = "Oversize.20x20";
aPrice[0] = "$299.00";
aPrice[1] = "$700.00";
aPrice[2] = "$2,999.00";
aPrice[3] = "$25,000.00";
// new - i fixed the declarations below
var aImage = [];
aImage[0] = "red.blue.3x5.jpg";
aImage[1] = "blue.yellow.5x8.jpg";
aImage[2] = "vintage.persian.7x10.jpg";
<html>
<!-- includes the othe script you created -->
<script type="text/javascript" src="data.js"></script>
<!-- we'll assume there are other tags such as <head> and <body> -->
<tbody>
<!-- your inline js -->
<script type="text/javascript">
// table header
document.write("<table border='1' rules='rows' cellspacing='0'>");
document.write("<tr>");
document.write("<th> </th><th>Name</th><th>Price</th><th>Order</th>");
document.write("</tr>");
// loop through aName aray & write results
for (var i = 0; i < aName.length; i++) {
document.write("<tr>");
document.write("<td>");
// new - i fixed the tag below
var imgSrc = "images/" + aImage[i];
document.write("<img src=" + imgSrc + " width='50' height='20'/>");
document.write("</td>");
document.write("<td>" + aName[i] + "</td>");
document.write("<td>" + aPrice[i] + "</td>");
// new -- not sure where you're getting the hyperlink url's from but i can help with this as well when you figure it out
// to create hyperlinks for products
document.write("<td><span class='link'><a href='#' title='price'>price</a></span>");
}
</script>
</tbody>
<!-- closing other tags -->
</html>
This code still would not display images and returned "Failed to load resource: net::ERR_FILE_NOT_FOUND" error in debugger. I fooled around with your updates and made it work by modifying one line:
document.write("");
changed to:
document.write("");
Now it works perfectly, thank you!!
It cannot find your image files. Check the paths you have set:
src="picture.jpg" = picture.jpg is located in the same folder as the current page
src="images/picture.jpg" = picture.jpg is located in the images folder in the current folder
src="/images/picture.jpg" = picture.jpg is located in the images folder at the root of the current web
src="../picture.jpg" = picture.jpg is located in the folder one level up from the current folder
Related
Here's a simple script that displays two latest posts under a certain label (in this example, the label "main"), in some section of a Blogger blog.
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML7").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?max-results=2&alt=json-in-script&callback=mainposts"></script>
Note that HMTL7 is the id that has been automatically assigned by Blogger to my HTML/Javascript-widget, which constitutes a div element by itself.
I have intentionally skipped including any post title variable in the script, so I'm just displaying the posts' content - no more, no less.
What I'd like to do is have two of these scripts for two different sections of my blog, where the second one would omit the two latest posts under the "main" label (same for both scripts), since they are already displayed by means of the first script.
What would I have to add to the second script to achieve this?
Add the start-index query parameter in the script src and initialize it from 3 (as the 1st and 2nd post would already be shown via the first instance of the code in the other section. The new code will look like -
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML99").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?start-index=3&max-results=2&alt=json-in-script&callback=mainposts"></script>
The exact ID of HTML widget will depend on your blog (mainly it will be different from HTML7)
Initialize for loop variable with 2 var i = 2; and maximum results 4 max-results=4
<script type="text/javascript">
function mainposts(json) {
var item="";
for (var i = 2; i < json.feed.entry.length; i++) {
var mainContent = json.feed.entry[i].content.$t;
item += '<div>' + mainContent + '</div>';
}
document.getElementById("HTML7").innerHTML = item;
}
</script>
<script src="http://www.MYBLOG.com/feeds/posts/default/-/main?max-results=4&alt=json-in-script&callback=mainposts"></script>
I'm working on a Blogger widget, trying to rid it of any deprecated or bad practices (based what I read on Stack Overflow), such as document.write
This was working:
<script type="text/javascript">
function introductory(json) {
document.write('<div id="intro-wrapper">');
var i;
for (i = 0; i < json.feed.entry.length; i++) {
var introTitle = json.feed.entry[i].title.$t;
var introContent = json.feed.entry[i].content.$t;
var item = '<h2>' + introTitle + '</h2><p>' + introContent + '</p>';
document.write(item);
}
document.write('</div>');
}
</script>
<script src="https://MYBLOG.blogspot.com/feeds/posts/default/-/intro?max-results=1&alt=json-in-script&callback=introductory"></script>
It displays the title and content (wrapped up within h2 and p tags, respectively) of one single post ( ...max-results=1... ), labeled "intro" ( .../-/intro?... ) by means of Blogger labels.
I've tested various alternatives, lining up my html elements prior to the js, then using getElementById, followed by either innerHTML or appendChild, or even lining up the elements inside the js, by means of createElement, but to no avail, really. Would it be possible for anyone to point me to the right direction?
P.S. I can hardly copy and paste all of my attempts in this question. There have been dozens of them, as I'm more or less clueless when it comes to javascript and I'm just experimenting my way forwards, so I've opted for merely posting the code that is actually working and asking for an alternative that does not utilize document.write, if that's indeed "bad practice".
I greet you at the beginning about trying to rid document.write
Create an element with a unique id before your JS code in the document, then select this element by its id getElementById and add your content to it using innerHTML
<div id="intro-wrapper"></div>
<script type="text/javascript">
function introductory(json) {
var item="";
for (var i = 0; i < json.feed.entry.length; i++) {
var introTitle = json.feed.entry[i].title.$t;
var introContent = json.feed.entry[i].content.$t;
item += '<h2>' + introTitle + '</h2><p>' + introContent + '</p>';
}
document.getElementById('intro-wrapper').innerHTML=item;
}
</script>
<script src="https://MYBLOG.blogspot.com/feeds/posts/default/-/intro?max-results=1&alt=json-in-script&callback=introductory"></script>
You can also use document.createElement instead of document.write.
Here is working example -
<script>
function introductory(json) {
var RecentPostContainer = document.createElement('div');
RecentPostContainer.className = 'RecentPostContainer';
for(i = 0; i < json.feed.entry.length; i++) {
var PostContainer = document.createElement('div');
PostContainer.className = 'PostContainer';
var PostTitle = document.createElement('h2');
PostTitle.className = 'PostTitle';
var PostTitleText = document.createTextNode(json.feed.entry[i].title.$t);
PostTitle.appendChild(PostTitleText);
PostContainer.appendChild(PostTitle);
var PostContent = document.createElement('div');
PostContent.className = 'PostContent';
PostContent.innerHTML = json.feed.entry[i].content.$t;
PostContainer.appendChild(PostContent);
RecentPostContainer.appendChild(PostContainer);
}
document.getElementById('RecentPostContainer').insertAdjacentHTML('afterend', RecentPostContainer.outerHTML);
}
</script>
<script id='RecentPostContainer' src="https://blogger.googleblog.com/feeds/posts/default/?max-results=1&alt=json-in-script&callback=introductory"></script>
Im reading in a flickr api list, and dynamically outputting into an unordered list format using some standard javascript. I have added functionality which enables you to toggle 'selected' class to the list.
How can i add cookie to the code which helps remember which list items i have selected when refreshing the page?
http://codepen.io/coolkingkhan/pen/PZvPOB
only pure javascript please IE8+
****** Javascript code *******
(function () {
var tags = 'london',
label = 'Small 320',
script = document.createElement( 'script' );
script.src ='http://api.flickr.com/services/feeds/photos_public.gne?format=json&jsoncallback=cb&tags=' + tags + '&label=' + label;
document.head.appendChild(script);
})();
function cb(data) {
// output the flickr images from api into img element within an unordered list
var output='<ul>';
for (var i=0; i < 9; i++) {
var imgURL = data.items[i].media.m;
output+='<li class="flickrlistitem">' + '<img src=' + imgURL + '/>' + '</li>';
}
output+='</ul>';
document.getElementById('flickrfeed').innerHTML = output;
// add click event on all items with the classname flickrlistitem
var anchor = document.querySelectorAll('.flickrlistitem');
for (var i=0; i < anchor.length; i++){
anchor[i].addEventListener("click", function(){
this.classList.toggle('selected');
}, false);
}
}
****** HTML code *******
<div class="main-container">
<div id="flickrfeed">
</div>
</div>
There was a similar question to this one a few minutes ago:
location.reload(), Javascript,HTML
Basically when the page reloads they set a cookie to read it later.... This approach should work.
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'm currently working on a dealer search for my company. I want to add some tabs, so that the cutomers can filter the dealers per state. This means that the divs for the states are created dynamically, because the information comes from a CSV file.
I add the information like this:
function erzeugenTab() {
var $tabsDiv = $("#mapstabs");
var linkList ='';
var divRegion ='';
var linkZahl = 1
for (var i = 0; i < unique.length - 1; i++) {
linkList = linkList + "<li>" + unique[i] + "</li>" ;
divRegion = divRegion + "<div id =\"tabs"+linkZahl+"\">Test123</div>";
linkZahl = linkZahl + 1;
}
linkList = linkList + "</ul>";
$tabsDiv.append(linkList);
$tabsDiv.append(divRegion);
$(function() {
$('#mapstabs').tabs();
});
}
However, no tabs are apearring. You can se it here.
Any idea what I"m missing?
Can you try removing the $ on $tabsDiv turning it into just var tabsDiv?
Also, I do not see an open ul tag
Can you try by removing function()?
$(function() {
$('#mapstabs').tabs();
});
to
$('#mapstabs').tabs();