I have the following function:
function displayResults(Items) {
$("#result").text("");
$("#result").append('<div class="car-offers">');
$("#result").append('<div class="purple"></div>');
$("#result").append('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
$("#result").append('<h3>titleeee</h3>'); // ' + Items[i].Title + '
$("#result").append('<span>Year: 2003</span>');
$("#result").append('<span>Milage: 172,000 Km</span>');
$("#result").append('<span class="price">53,000 QR</span>');
$("#result").append('Link');
$("#result").append('</div>');
$("#result").append('<div class="car-offers">');
$("#result").append('<div class="purple"></div>');
$("#result").append('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
$("#result").append('<h3>titlee22</h3>'); // ' + Items[i].Title + '
$("#result").append('<span>Year: 2003</span>');
$("#result").append('<span>Milage: 172,000 Km</span>');
$("#result").append('<span class="price">53,000 QR</span>');
$("#result").append('Link');
$("#result").append('</div>');
}
my problem is that at run-time the html is being displayed like: <div class="car-offers"></div> so all the page is being messed up
You cannot append incomplete fragments of HTML with .append(). Unlike document.write, jQuery's .append() method parses the passed string into elements before appending them to the DOM.
So when you do:
$("#result").append('<div class="car-offers">');
jQuery parses the given string into a div element and assigns the car-offers value to its className property, then appends the newly created element to the #result element.
Appending the whole HTML string in a single operation will fix that, so jQuery knows how to parse the given string correctly.
Personally, I wouldn't suggest putting that much HTML inside of a JS file. You can consider putting that inside of a div with display:none then simply call .show() on it. Or have it initially in the page, .detach() it storing in a variable and .append() it back when necessary.
You can use a array with join to solve this
function displayResults(Items) {
$("#result").text("");
var array = [];
array.push('<div class="car-offers">');
array.push('<div class="purple"></div>');
array
.push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
array.push('<h3>titleeee</h3>'); // ' + Items[i].Title + '
array.push('<span>Year: 2003</span>');
array.push('<span>Milage: 172,000 Km</span>');
array.push('<span class="price">53,000 QR</span>');
array.push('Link');
array.push('</div>');
array.push('<div class="car-offers">');
array.push('<div class="purple"></div>');
array
.push('<img src="images/caroffer.jpg" alt="" title="" width="213" height="117" />');
array.push('<h3>titlee22</h3>'); // ' + Items[i].Title + '
array.push('<span>Year: 2003</span>');
array.push('<span>Milage: 172,000 Km</span>');
array.push('<span class="price">53,000 QR</span>');
array.push('Link');
array.push('</div>');
$("#result").text(array.join(''));
}
This is an issue I've just come across too. An option is to create the div containers first in a loop then populate them after as you require:
for(var i = 0; i < 12; i++){
$(el).append('<li class="scene-block"></li>'); // create container li tags
//fill empty li tags with content
for(var j = 0; j < 2; j++){
$(el).find('li').last().append('<div class="select-a-scene-bg"></div>');
}
}
Related
My JavaScript script is not allowing to be marked up semantically. As you can see in my script below, I am using Schema.org and RDFa.
The problem is that when I validate my page, only the part before the append function is validated. This means that only type, headline, publisher and datePublished comes up.
How can I fix it? I suspect the problem here is the append function.
$(document).ready(function(){
$.getJSON(webhose_request, function(results){ //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
$(".webhose").append('<div vocab="http://schema.org/" typeOf="Article"><div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div><div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div></div>');
if(results.posts[i].thread.author){
$(".webhose").append('<div class="whpublished"><b>By:</b> <span property ="author">'+results.posts[i].thread.author+'</span></div>');
}
$(".webhose").append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> '+results.posts[i].thread.published.substring(0,10)+'</p></span></em> </div>');
//we check if there is an image for this posts then display
if(results.posts[i].thread.main_image){
$(".webhose").append('<div class="whimage"><img property="image" src="'+results.posts[i].thread.main_image+'" height="125" width="200"/></div>');
}
$(".webhose").append('<div property="articleBody" class="wharttext">'+articletext.substr(0,500)+'... <div class="whlink"><a property="url" href= '+results.posts[i].thread.url+'> Read full article »</a></div></div><br>');
}
});
});
I think the issue is that most of the parts of the article aren't in the <div vocab="http://schema.org/" typeOf="Article"> element. This can be shown to be true if one indents HTML from the first append:
<div vocab="http://schema.org/" typeOf="Article">
<div property="headline" class="whtitel">'+results.posts[i].thread.title_full.substring(0,110)+'</div>
<div class="source"><b>Source:</b><span property="publisher"> '+results.posts[i].thread.site+'</span></div>
</div>
In the following I have changed the code to create the article div and then append the contents to it and then append it to the document. The following is untested but I think it might work.
$(document).ready(function() {
$.getJSON(webhose_request, function(results) { //send request to API and store results in "results"
//parse the results' from the JSON response and display them //in a div element for example <div class='webhoseapi'></div>
//we can loop to display all results in a for loop or using the results.posts.lenght; or just display a few.
for (var i = 0; i < 10; i++) {
// you need to read the JSON results to know how to parse them, for example here results.posts[i].text
var articletext = results.posts[i].text;
// we use regular expressions REGEX to replace any new line '\n' and carriage return '\r' with html breaks </br>
articletext = articletext.replace(/(?:\r\n|\r|\n)/g, '</br>');
var article = $('<div vocab="http://schema.org/" typeOf="Article"></div>');
article.append('<div property="headline" class="whtitel">' + results.posts[i].thread.title_full.substring(0, 110) + '</div>')
article.append('<div class="source"><b>Source:</b><span property="publisher"> ' + results.posts[i].thread.site + '</span></div>');)
if (results.posts[i].thread.author) {
article.append('<div class="whpublished"><b>By:</b> <span property ="author">' + results.posts[i].thread.author + '</span></div>');
}
article.append('<div class="whpublished"><b>Date published:</b><em><span property="datePublished"> ' + results.posts[i].thread.published.substring(0, 10) + '</p></span></em> </div>');
//we check if there is an image for this posts then display
if (results.posts[i].thread.main_image) {
article.append('<div class="whimage"><img property="image" src="' + results.posts[i].thread.main_image + '" height="125" width="200"/></div>');
}
article.append('<div property="articleBody" class="wharttext">' + articletext.substr(0, 500) + '... <div class="whlink"><a property="url" href= ' + results.posts[i].thread.url + '> Read full article »</a></div></div><br>');
$(".webhose").append(article);
}
});
});
Hello I am having some trouble getting some HTML links to add to my HTML page. I have tried searching around but nothing has helped thus far.
My page will initially load a snippet:
<div style="display: inline-block; color: rgb(0, 255, 144)">Roster: </div>
<span id="teamRoster"></span>
<br />
Which appears like Roster: in the View
Right now my snippet has been modified to add names:
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + teamRoster[i] + ", ";
}
$("#teamRoster").text(rosterListings);
Which will update my View to Roster: John, Frank, Susan, ect..
However, I am trying to now add <a href> tag's around each person and turn them all into actual links. My attempt looks like this
var rosterListings = "";
for (var i = 0; i < teamRoster.length; i++) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
}
$("#teamRoster").text(rosterListings);
which displays as
Roster: <a href='#'>John</a>, <a href='#'>Frank</a>, ect..
I understand why this occurring since I am setting actual text/strings, but is there a way to convert this string into HTML elements? I have tried a few $.parseHTML code snippets that I found from Googling but I must be implementing them all wrong.. :(
Any help appreciated, Thank you!
Well, solution is quite obvious
Just replace
$("#teamRoster").text(rosterListings);
With:
$("#teamRoster").html(rosterListings);
Because if you use it as a text then it will treat it as the text and if you write html then it will treat it as a html
The problem is that you're using .text(), which will insert only text into the span, as seen here.
You need to use .html() if you want what is inserted to actually render as HTML.
So, try this:
$("#teamRoster").html(rosterListings);
Demo
Also note that the way you've set up your for loop causes an extra comma to be placed at the end of the list; I've fixed that here by checking whether it's the last element:
if (i !== teamRoster.length - 1) {
rosterListings = rosterListings + " <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>,";
} else {
rosterListings = rosterListings + " and <a href='" + idList[i] + "'>" + teamRoster[i] + "</a>.";
}
As Just code points out, you want to use the html method, not the text method. html() is jQuery's wrapper for innerHTML, which injects the string as html.
Here is a jsFiddle showing the difference:
http://jsfiddle.net/89nxt/
$("#teamRosterHtml").html("<a href='#'>John</a> <a href='#'>Frank</a>");
$("#teamRosterText").text("<a href='#'>John</a> <a href='#'>Frank</a>");
I am trying to get the information in a image alt attribute from one page (source) and insert it into another page (same server) with javascript/jquery. A for loop will extract source URLs to extract the information from. It works until I get to the jquery load action... I'm looking for a way to extend the id reference of the photo to get the information from the alt attribute on the source HTML page. Please advise and thank you in advance!
-------------------------------- source HTML page...
<img id="photo" alt="Text to be loaded into another page" src="pathToImage.jpg">
<script>
countStart = 0;
// Begin loop to write each section from an array reference of page URLs/sources
for (var i = 0; i < Array.length; i++) {
// The "replaceURLs" array value/variable yeilds the URL of the pages to extract from
replaceURLs = Array[i].value;
// write a div where the information will be inserted
document.write('<div id="prodImgAlt' + countStart + '"></div>');
// jquery load remote HTML
$( "#prodImgAlt" + countStart ).load( replaceURLs + " #photo" );
// here is where I'm getting stuck... I need to modify the "#photo" reference to extend to the information in the img alt attribute on the source HTML page... than that information will be stuffed int the div #prodImgAlt.
countStart++;
}; // end loop
</script>
Try
$.each(Array, function (idx, url) {
var $div = $('<div />', {
id: 'prodImgAlt' + idx
}).appendTo('body');
$.get(url, function (html) {
var $html = $(html),
$img = $html.find('img');
$div.append('<div>' + $img.length + ',' + $img.attr('alt') + '</div>');
$html.find($img.attr('alt')).appendTo($div);
}, 'html');
})
I'm on a .NET 4.0 environment using jQuery and Visual Studio to write everything, but neither of these facts should matter that much except how to populate the XML data.
I'm starting out with this script which has a lot of markup in it. My task is to get the markup out of the script and to populate the the XML data into the markup in its proper place. I'm trying to keep the presentation and behavior layers as separate as possible by doing this.
function addIcons(IconType) {
var li ="";
var onclickMethod="";
for (var item in hashObject) {
var thumbNail = item.split("_");
if (thumbNail[0] == IconType +"ThumbNail") {
var imagePath = baseUrlThumbNailImages + hashObject[item];
li = li + "<li onclick=IconClick('" + IconType +"',"+ thumbNail[1] + ")><img src=\"" + imagePath + "\" alt=\"" + IconType + " shape\"></li>\n";
}
}
$("#" + IconType + "ThumbNailShapes").append(li);
}
Here's example markup I want as final result:
<ul>
<li onclick="IconClick('Item',1)">
<img src="/images/image_1.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',2)">
<img src="/images/image_2.png" alt="Item shape" />
</li>
<li onclick="IconClick('Item',3)">
<img src="/images/image_3.png" alt="Item shape" />
</li>
</ul>
While I know I need to take out the line of code that starts li = li + ..., I'm also not familiar enough with OOP to understand how to write a for loop to populate the markup.
So there's two factors that I am not sure how to code:
The blank markup - does the markup need variables to populate it or should javascript do this automatically?
The javascript - I don't know how to recode the javascript to find each list item and image tag to populate the various data.
Do I need the markup to be blank like this, where all the variable data is not there yet?
<ul id="IconThumbnailShapes">
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
<li onclick="">
<img src="" alt="shape" />
</li>
</ul>
I appreciate the insight and help.
I would do it like this.
Let's suppose we have a container DIV#foo where all this code has to reside.
<div id="foo"></div>
We then do this:
$(function() {
// DOM ready
$('#foo').on('click', '#IconThumbnailShapes li', function() {
// Do whatever you have to do with icon
// Second argument there '#IconThu... li' means the event will be trigerred
// as soon as you add your icons, but they don't have to be there
// right now.
});
function addIcons(iconType) {
var s = '<ul id="IconThumbnailShapes">'
var l = '<li><img src="$SRC" alt="$ICON shape" /></li>'
var data = [{...}, {...}, {...}];
var len = data.length;
var datum;
for (var i = len; i; i--) {
datum = data[len - i];
s += l.replace('$SRC', datum.src).replace('$ICON', iconType);
}
s += '</ul>';
$('#foo').html(s);
}
});
So, we do it like this, because we don't want to fire jQuery stuff in the for loop. That kills performance. Instead we set up a deferred even handler for click on the conainer DIV#foo, and we shove the whole bunch of markup into the container as a string.
I want to display image user click from image link in a for loop to a div.
my for loop is as follows.
<a href='' name=my_image[i]
onclick='disp_image('link_image_url')'id=my_image[i] class='popup-open'><img src=my_image[i] width='80' height='65'></a>;
and my javascript function
<script language=\"javascript\">
function disp_image(url){
document.getElementById('image').innerHTML ="<img src=url width='100' height='105'>";
;}
</script>
</script>
However it is not being load in my div content
<div id="image"></div>
can someone has an idea how can i display selected image in a div content dynamically
Use this:
var _leng = my_image.length
, td = "<td><a href='#url#' onclick='displaying(/image#url#)' id='/image#url#'><img src='#url#' width='80' height='65' /></a></td></tr><tr>"
, i;
for (i=0; i < _leng; i++) {
str += td.replace(/#url#/g, my_image[i])
}
Check this example:
http://jsfiddle.net/hMfRG/
You have mismatched quotes so the string isn't being generated properly, or at all... you probably have errors in the console.
str += "<td><a href='" + my_image[i] + " onclick='displaying()' id='/image" + my_image[i] + "'><img src='" + my_image[i] + "' width='80' height='65' /></a></td></tr><tr>";
You can't use these special quotes ‘’ or ”, only use these single or double quotes ' or ".
Example:
document.getElementById('image')
You have displaying() in the loop but below, its called displayImage(). Also, the function expects an argument which you're not supplying in the call.
Look at the syntax highlighting of your post. You can clearly see that your quotes are all over the place. For instance, you have src='"+url+'", which is wrong. You also have "smart quotes" in places. Fix the quotes and it should stop throwing syntax errors.
But most importantly, your onclick function calls displaying(), whereas the function is called displayImage and takes an argument.
I've done it this way:
<div id="result" style="width:450px;height:296px;">
<img name="main" src="/images/image.jpg" alt="">
</div>
function change_pic(img_name,img_src)
{
document[img_name].src=img_src;
}