I have this code:
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
'<div>' + v.points + '</div>' +
'<div>' + v.other + '</div>' +
'</a>'
);
});
Into the user grid div, I append the string with the values taken from data.
v.points and v.other are the numbers.
To this moment, everything works just fine. But what I need is to embed the for loop into the divs. In the places where I have v.points and v.other I want to put two simular FOR loops.
for(var i = 0; i < v.points; i++) {
//here is the html line that should be passed to the div, where v.points are now
<div>This is the point</div>
}
And almost the same for the v.other. Only with another line that should be pasted.
So basically how can I do that? I was trying to paste this loops right inside the "append()" but that didn't work out. I was also trying to create a variable inside of the loop and pass it in to the append, but got only one result, instead of all that I have needed.
I'm not sure if this is what are you looking for, this code prints 5 "This is your point" and 3 "This is your other" inside the anchor.
var data = [
{
points: 5,
other: 3
}
]
function printPoints(vPoints){
var str = "";
for(var i=0; i<vPoints; i++) {
str+="<div>"+"This is your point"+"</div>";
}
return str;
}
function printOther(vOther){
var str = "";
for(var i=0; i<vOther; i++) {
str+="<div>"+"This is your other"+"</div>";
}
return str;
}
$.each(data, function(i,v){
$('#user-grid').append(
'<a href="my_urls">' +
printPoints(v.points)+
printOther(v.other)+
'</a>'
);
});
See it on action here
Related
I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.
I am adding buttons based on an array. The problem I am having is that every time I add another name to the array, it prints out all the buttons not just the one I added. I am wondering how would I erase all the old buttons before I add the array of buttons.
Here is my code
socket.on('usernames', function(data){
console.log(data);
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
// $users.html(html);
});
Below is an image. Test is the name of the first button and every time I add a new button it prints the entire array again. Is there a way to delete the old buttons?
Use the empty() method before you loop:
socket.on('usernames', function(data){
var $contentWrap = $("#contentWrap").empty();
for (i = 0; i < data.length; i++) {
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($contentWrap);
}
});
Also note that you can improve performance and tidy the code by creating a single HTML string and setting the html() property to only require one DOM call. Try this:
socket.on('usernames', function(data){
var html = data.map(function(value) {
return '<input type="button" value="' + value + '"/></br>'
}).join('');
$('#contentWrap').html(html);
});
You can call .empty() on the parent element before appending the elements again.
$("#contentWrap").empty();
for(i=0; i <data.length; i++){
// html += data[i] + "<br/>";
$input = $('<input type="button"/></br>');
$input.val(data[i]);
$input.appendTo($("#contentWrap"));
}
I got this data that are am getting from the database using an xmlhttprequest.
[{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}]
My main aim is to arrange the data in a column form as follows:
description location name created_at
The square brackets confuse me a little bit but it seems like a javascript array but i just cant parse it correctly.
You could just loop through it, and access each element. Here is an example formatting it into some HTML tables.
var data = [{"description":"welcome","location":"Nairobi","name":"Equity Bank","created_at":"2013-02-07 21:12:45"},{"description":"very nice job","location":"Kisumu","name":"Equity Bank","created_at":"2013-02-16 12:19:46"},{"description":"welcome all","location":"nairobi","name":"Equity Bank","created_at":"2013-02-16 13:28:26"},{"description":"Very nice","location":"Nairobi","name":"Equity Bank","created_at":"2013-07-08 01:50:11"},{"description":"bad job","location":"eldoret","name":"Safaricom","created_at":"2013-02-03 00:00:00"},{"description":"very nice job","location":"mombasa","name":"Deep Africa","created_at":"2013-02-05 00:00:00"}];
var results = document.getElementById('results');
htmlString = '<table><tr>';
for( a=0; a<data.length; a++) {
htmlString = htmlString + '<tr><td>' + data[a]['description'] + '</td><td>' + data[a]['location'] + '</td><td>' + data[a]['name'] + '</td><td>' + data[a]['created_at'] + '</tr>';
}
htmlString = htmlString + '</table>';
results.innerHTML = htmlString;
There's a jsfiddle at http://jsfiddle.net/R63BJ/
As If ur using a XMLHTTRequest you will get the data in responesText
var jsonData=eval('('+responseText+')');
var text="<table><tr><th>description</th><th>location</th>" +
"<th>name</th><th>created_at</th></tr>";
for(var i=0;i<jsonData.length;i++){
text+="<td>"+jsonData[i].description+"</td>";
text+="<td>"+jsonData[i].location+"</td>";
text+="<td>"+jsonData[i].name+"</td>";
text+="<td>"+jsonData[i].created_at+"</td>";
text+="</tr>";
}
text+="</table>"
document.getElementById("tag").innerHTML="";// make sure that data is not Present
document.getElementById("tag").innerHTML=text;
and In the Jsp Page:
<div id="tag"></tag>
I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;
Okay, so I'm parsing some data from a webservice here.
I'm just throwing in a bunch of values from a json object into html, however! i need to check if a certain json value is set to true or false. If so, i need to remove/add a word.
So i basicly i need to get a bunch of prices out. That's easy
$.each(data.d, function (i, service) {
$(".services").append('<li class="classes here"><p class="servicePrice">'+service.Price+' kr</p><div class="serviceNames">' + service.Name +'<br />' + service.FirstAvailableSlot + '</div>
});
Now! i have to check for this value called FromPrice in the JSON object. And if that is true, then the word 'fra' should be added to the beginning of the the p tag with the class servicePrice.
Now, i certainly can't do it like this.
$.each(data.d, function (i, service) {
if (service.PriceFrom == false) { $('.servicePrice').prepend('fra '); };
$(".services").append('<li class="classes here"><p class="servicePrice">'+service.Price+' kr</p><div class="serviceNames">' + service.Name +'<br />' + service.FirstAvailableSlot + '</div>
});
That's just gonna add the word a whole bunch of times depending on how many loops we go through.
i've tried doing it the whole if thing inside the servicePrice tag. But that just gave me a whole lot of javascript parse errors.
Anyone wanna throw this guy a bone?
Update: I'm still not sure about this, but is this what you're looking for?
$.each(data.d, function (i, service) {
var txt = (service.PriceFrom == false) ? "fra" : "";
$(".services").append('<li class="classes here">'+txt+'<p class="servicePrice">'+service.Price+' kr</p><div class="serviceNames">' + service.Name +'<br />' + service.FirstAvailableSlot + '</div>');
});
If I understood correctly then this should work.
var isFalse = false;
$.each(data.d, function (i, service) {
if (service.PriceFrom == false && !isFalse) {
$('.servicePrice').prepend('fra ');
isFalse = true;
};
$(".services").append('<li class="classes here"><p class="servicePrice">'+service.Price+' kr</p><div class="serviceNames">' + service.Name +'<br />' + service.FirstAvailableSlot + '</div>
});