Hi i would like to create an array from the title and src of an image set. Then append it to a list, then clear the array (the images in the set changes) then clear the array and the list. repeat it again and again as the images change in the set.
Here is the HTML:
<div id="imageholder">
<img src="images/a001.png" title="orange"/>
<img src="images/a002.png" title="red apple"/>
<img src="images/a003.png" title="green apple"/>
<img src="images/a004.png" title="red apple"/>
</div>
<ul id="list"></ul>
and here is the code:
title_array = [];
src_array = [];
function sumarychange() {
$("#imageholder img").each(function() {
// pushing each values into arrays
title_array.push($(this).attr("title"));
src_array.push($(this).attr("src"));
// i think this part will append the content in the arrays
var list = $('#list');
var existing_item = $('#list_'+ title);
// removing items with the same titles
if (existing_item.length < 1){
var new_item = $('<li />');
new_item.attr('id', 'list_'+ title);
new_item.html('<div>' + title + '</div><img src="' + src + '" />');
list.append(new_item);
}
});
// i think this will set the arrays back to empty
title_array.length = 0;
src_array.length = 0;
}
this is just a sample. In actual the image has more tags. i have no clue how to empty out the list when this function is called again. im just learning coding now and i have no idea how to correct this to make it work.
This looks to me like an XY problem.
Judging from your example code above as well as your previous question, I'm guessing what you're trying to do is update a list of entries based on the attributes of an existing set of elements, but with items with duplicate titles only displayed once.
Assuming I got that right, here's one way to do it: (demo: http://jsfiddle.net/SxZhG/2/)
var $imgs = $("#imageholder"), $list = $("#list");
function summary_change() {
// store data in tmp obj with title as key so we can easily ignore dups
var store = {};
$imgs.find("img").each(function() {
if (store.hasOwnProperty(this.title)) return; // ignore dup title
store[this.title] = this.getAttribute("src");
});
$list.empty(); // empty the list
for (var title in store) { // add new list items
$("<li>")
.append($("<div>", {"text":title}))
.append($("<img>", {"src":store[title]}))
.appendTo($list);
}
}
Note that if more than one image has the same title, only the src of the first one is used in the summary results. If you wish to use the src of the last item found, simple remove the line if (store.hasOwnProperty(this.title)) return;.
Related
I am new to jQuery and I am working with an API to do the following.
Get Multiple values from the API like name, place, weather forecast etc.
I have a bootstrap structure with the following code:-
<div id="place_here" class="row">
</div>
I want to place the data that I get from the API in this DIV.
Only thing that I want to do is get put all that data into a single div and place that div into above row div to create a beautiful table like structure. Something like this:-
var str = '<div class="col-md-4">' + newoverview + '</div>';
(newoverview is a string from JSON that I get. However that is only a single value that I want to place in my div class = "col-md-4" tag above. I want to insert more values as well.
Problems:-
I cannot(or don't know) how to use global variable in JQuery. Whenever I log a variable value in console it give me a null . I know that's because JSON is asynchronous but I don't know a work around this.
I tried using multiple functions and passing values one by one and adding div by div. However that is not doing what I want to do and gives a messed up structure.
How can I collect all the required values that I get in a JSON and combine them in a single div and place it in a div in my HTML structure.
Edit:- Code
$(document).ready(function(){
$("#Search_Button").click(function() {
var name;
name = $("#value").val();
if(!name){
console.log("Enter a name");
}
search(name);
});
function search(name){
var url = "url_here";
$.getJSON(url,function(data){
$.each(data.results,function(i,j){
displayImage(j.path);
displayOverview(j.id);
});
});
}
function displayOverview(id){
var url = "url_here";
$.getJSON(url,function(data){
var overviewx = data.overview;
var newoverview='';
for(var x=0;x<overviewx.length && x<100 ;x++){
newoverview+=overviewx[x];
}
var str = '<div class="col-md-4">' + newoverview +
'</div>';
$("#place_here").append(str);
});
}
function displayImage(id){
var url = "url_here";
var str = '<img src="' + url + '"</img>';
$("#place_here").append(str);
console.log(str);
}
});
I want to place both(and maybe more) tags in a single div from displayOverview and from displayImage and place that div into my main HTML Structure.
This is just an exemple !
to prevent asynchronous processing,we use callbacks
function getItem(){
var dfd = jQuery.Deferred();
var url_to_json = 'json/test.json';
$.getJSON(url_to_json, function(data) {
dfd.resolve(data);
});
return $dfd.promise();
}
when you need a the response you just :
getItem.done(function(data){
console.log(data);
});
enter code hereI have an html UL control that gets dynamicaly populated with LI (list items).
I want a javascript function to process the items of the list and need a csv of all the list items.
I am trying this and getting errors:
javascript:
var ulTags = document.getElementById("basic_tag_handler");
var listItem = ulTags.getElementsByTagName("li");
var stringOfTags = '';
for (var i = 0; i < listItem.length-1; i++) {
stringOfTags += listItem[i].innerHTML & "," );
}
alert (stringOfTags);
html:
<ul id="basic_tag_handler" runat ="server" ></ul>
You've a syntax error when you have &, I suppose, you meant +. Also, you need to remove the trailing comma, but however better way would be to use Array.map and Array.join
var stringOfTags = [].map.call(listItem, function(elm){
return elm.innerHTML;
}).join(",");
Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:
A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.
The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:
<ul data-role="listview" id="treesUL" data-inset="true" style="visibility: hidden">
<li id="treesLI">
<div class="resultNames">
<span class="donorName">Donor</span>
for
<span class="honoreeName">Honoree</span>
</div>
<div class="resultInfo">
<span class="treeName">common</span>
on:
<span class="donationDate">Date</span>
</div>
<div class="resultDedication">
<span class="dedicationText">Dedication</span>
</div>
</li>
</ul>
The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
//Retrieve the JSON encoded array, which is stored at index-key: media
var text = requestObj.responseText;
//alert(text);
var myTrees = jQuery.parseJSON(text).media;
$('#treesUL').text('');
//Alert the number of rows, for testing purposes
alert(myTrees.length + " results.");
//Loop through the JSON array, and add each element to a <li>, which is then added to the <ul>
for(var i = 0; i < myTrees.length; i++)
{
var tree = myTrees[i];
var li =$('#treesLI').clone();
li.removeAttr('id');
li.appendTo('#treesUL');
//li.find('.treeLink').setAttribute("href", "somelink url");
li.find('.donorName').text(tree['donor']);
li.find('.honoreeName').text(tree['honoree']);
li.find('.dedicationText').text("'" + tree['dedication'] + "'");
if (tree['common'] != '')
li.find('.treeName').text(tree['common']);
else
li.find('.treeName').text("Unknown Species");
li.find('.donationDate').text(tree['date']);
li.data('treeID','tree'+i);
}
}
}
I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';
for(var i = 0, length = myTrees.length; i < length; ++i)
{
var tree = myTrees[i];
html += '<li class="treesLI" onClick="somefunction('+ tree.id+')">';
html += '<div class="resultNames"><span class="donorName">' + tree.donor + '</span>';
html += 'for <span class="honoreeName">'+ tree.honoree + '</span></div>';
html +='</li>';
$('#treesUL').append(html);
}
As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){
});
Some other observations:
You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8
I'm trying to learn HTML and Javascript/jQuery. If I have a container which holds a title, an image, a description and a number, then I want to create a new container with the exact same format (except the values will be different), how is this commonly done?
This is an example of the format I'm looking for in each item.
<li>
<div>
<div>
Image Name
</div>
<div>
<a href=URL>
<img src='image_url'>
</a>
</div>
<div>
Description
</div>
<div>
num_comment Comments
</div>
</div>
</li>
Do I just create a string and concatenate with the actual values for the image, then add that string to some variable I've saved called html_content, and then set the html value to html_content? Is that the common way of doing this or is there a better way?
EDIT
To give a better idea of what I'm currently doing, here's the javascript:
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
};
$('pics').html(html);
}
In jQuery you just have to use the append() function to add on to something.
You could do something like...
$('select element').append('<li><div>....etc.');
and where you want a different value you can use a variable.
You can use .clone() and create a copy of this, then iterate through the cloned object and change what you need:
var $objClone = $("li").clone(true);
$objClone.find("*").each(function() {
//iterates over every element. customize this to find elements you need.
});
To change the image source you can do:
$objClone.find("img").attr("src", "new/img/here.jpg");
Fiddle demoing the concept: http://jsfiddle.net/H9DnA/1/
You may find it useful to explore some of the JavaScript templating libraries. The essential idea is that you create a template of your markup:
<li>
<div>
<div>
{{name}}
</div>
<div>
<a href="{{url}}">
<img src="{{imageUrl}}">
</a>
</div>
<div>
{{description}}
</div>
<div>
{{comments}}
</div>
</div>
</li>
Then you merge it against some associated matching object and insert it into your document:
{ name: 'Image Name',
url: 'http://example.com',
imageUrl: 'http://example.com/image.jpg',
description: 'Description',
comments [ { text: 'Comment' } ]
}
function render(pics)
{
var theList = document.getElementByid("LIST ID");
for (var i in pics){
var listItem = document.createElement('li'); // Create new list item
var nameDiv = document.createElement('div'); // Create name DIV element
nameDiv.innerHTML = pics[i].name; // Insert the name in the div
var img = document.createElement('img'); // Create Img element
img.setAttribute('src',pics[i].src); // Assign the src attribute of your img
var imgDiv = document.createElement('div'); // Create Img Div that contains your img
imgDiv.appendChild(img); // Puts img inside the img DIV container
var descDiv = document.createElement('div'); // Create Description DIV
descDiv.innerHTML = pics[i].description; // Insert your description
listItem.appendChild(nameDiv); // Insert all of you DIVs
listItem.appendChild(imgDiv); // inside your list item
listItem.appendChild(descDiv); // with appropriate order.
theList.appendChild(listItem); // Insert the list item inside your list.
}
}
I think this will work just fine:
$('#button').click(function () {
var html1 = '<li><div><div>';
var html2 = '</div><div><a href="';
var html3 = '"><img src="';
var html4 = '"></a></div><div>';
var html5 = '</div><div>';
var html6 = '</div></div></li>';
function render(pics){
for (var i in pics){
html = html + html1 + pics[i].name + html2 + pics[i].image_url + html3 + ...
$("ul").append(html);
}
}
// call render
});
I didn't do a test run on your code so there might be an error somewhere. My tweak adds this line $("ul").append(html); inside your loop
I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>