Dynamically creating unique link or button for each result of a database query result - javascript

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

Related

how to get CSV from items of a html list control?

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(",");

Simple ToDo-List doesn't work

My ToDo List dont wanna work the way i want. I've just been working with JavaScript for 2 weeks sthis is very new to me, therefor the code maybe doesnt look that nice.
The result comes out wrong. If I type in "buy food" the first line gonna show just that, but the next time I wanna add "walk the dog", then it displays
buy food
buy food
walk the dog
I hope you understand my problem. It also ends the unordered list tag after the first click and adds the rest of the things in another.
Here's the JavaScript:
var taskList = [];
var text = "<ul>"
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The issue is you're closing the ul tag after adding each item. Instead of concatenating raw HTML, consider using element objects and appending, and using a text node object to handle the user input - this removes the possibility of a DOM Based XSS vulnerability.
window.onload = function() {
var taskList = [];
var container = document.getElementById("todoList");
document.getElementById("add").onclick = addToList;
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
var ul = document.createElement('ul');
var li;
for (i = 0; i < taskList.length; i++) {
li = document.createElement('li');
li.appendChild(document.createTextNode(taskList[i]))
ul.appendChild(li);
}
container.innerHTML = '';
container.appendChild(ul);
}
};
Task:
<input id="toDoTask" /> <input type="button" id="add" value="Add" />
<div id="todoList">
</div>
You should not use the innerHtml. This replace all the text of your content. You should just add the li to your ul.
You can do that by using the append function by jquery Append
your <ul> must contain an id like this <ul id="toDoList">
then you make $("#toDoList").append("yourTask");
yourTask must contains the li.
With this, you don't need to iterate on all your element list
Not sure, but you seem to keep adding to text the second time, so text will be something like <ul><li>buy food</li></ul><li>buy food</li><li>walk the dog</li></ul>, which is invalid HTML by the way, but gets outputted anyway...
On each call of function addToList() you should reset the variable text.
For example:
function addToList() {
var task = document.getElementById("toDoTask").value;
taskList.push(task);
text="";
for(i = 0; i < taskList.length; i++){
text += "<li>" + taskList[i] + "</li>" ;
}
text += "</ul>";
document.getElementById("todoList").innerHTML = text;
}
The whole list of items in array will appends to variable text on each call.

Another way to display JS on PHP page?

i am retrieving some information from Google's API and placing them in a single variable, and then inserting them to a div in the DOM like so:
$(function() {
// Load the info via Google's API
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641/activities/public?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += '<article>';
html += '<img src="'+data.items[i].actor.image.url+'">';
html += '<p>'+data.items[i].title+'</p>';
html += '<p>'+data.items[i].published+'</p>';
html += '</article>';
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
My question is: is there a way to store every piece of information in each of its own variable, and then get the information individually by echoing the variable? So i dont have to hardcode all that HTML.
back in the days I would do:
<div id="google-posts-container">
<article>
<img src="{{image}}">
<p>{{title}}</p>
<p>{{published}}</p>
</article>
</div>
<script type="text/javascript">
// render a template (replace variables and return html)
function renderTemplate(tmpl, data){
for (k in data){
while(tmpl.indexOf('{{'+k+'}}') > -1){
tmpl = tmpl.replace('{{'+k+'}}', data[k]);
}
}
return tmpl;
}
$(function(){
// our template
var template = $('#google-posts-container').html();
$('#google-posts-container').html(''); // or clear()
$.getJSON("https://www.googleapis.com/plus/v1/people/103039534797695934641"
+"/activities/public"
+"?maxResults=5&key=AIzaSyBaDZGM-uXuHc-VZZ2DINzVBcIDMN_54zg", function(data) {
// Variable to hold the HTML we'll generate
var html = '';
// how many posts we're displaying on the page
var numberOfPosts = 3;
// Loop over the results, generating the HTML for each <li> item
for (var i=0; i<numberOfPosts; i++) {
html += renderTemplate(template, {
image : data.items[i].actor.image.url,
title : data.items[i].title,
publish : data.items[i].published
});
}
// Insert the generated HTML to the DOM
$('.google-posts-container').html(html);
});
});
</script>
nowadays I use angularjs
About comment by 'galchen' - don't use angular.js for serious &(or) big projects. Just look at source code.
(can't add sub comment, thats why i wrote to main branch)

looping and prepending javascript to html

I am going to have to repost my previous question because I need to reformulate what I need.
So, here it goes.
I have a webpage containing some list items,
HTML
<div class="container">
<p>Items are ordered Alphabetically and I want the text to be untouched</p>
</div>
All of these list items are contained in a folder on my computer. What I want to do is not have to manually input the ../Html/1.html , ../Html/2.html, ... instead, I was hoping to find a script to do the job for me.
All the items are numbered in numerical order, starting at 1 all the way to 100.
So I know iterating using i++ might come in handy in a loop. But I really dont know more than that!
Use this:
<div id="theContainer" class="container">
<p>Items are ordered Alphabetically and I want the text to be untouched</p>
</div>
<script>
window.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('theContainer'), i, p, s;
var numStart = 1, numEnd = 100;
var path = '../Html/*.html'; //use "*" to substitute the number
for (i = numStart; i <= numEnd; i++) {
p = path.replace(/\*/,i);
s += '<li>' + p + '</li>';
}
container.innerHTML = container.innerHTML + '<ol>' + s + '</ol>';
}, false);
</script>

how to appending content from array and then clear it in jQuery

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;.

Categories