Append JavaScript array data into div - javascript

I have the following JavaScript array data:
[{'id:1'},{"info":"Name"}"]
[{'id:2'},{"info":"LastName"}"]
How do I loop through this and insert the data into a div? I tried something like this,but no success:
for(var i=0; msg.length<i; i++){
$('#results_box').append(msg[i].id);
$('#results_box').append(msg[i].info);
}

Correct your JSON to proper format:
var array = [{id:1,info:"Name"},{id:'2',info:"LastName"}]
then:
for(var i=0; i<array.length; i++)
{
$('#results_box').append('<p>' + array[i].id + '=' + array[i].info + '</p>');
}
html
<div id="results_box"></div>
Fiddler

Related

Accessing object values with generic method

I'm doing some refactoring and trying to create a generic method which is able to populate given dropdowns with object data. However I'm coming up against an issue regarding how to make accessing different object data generic. For example:
Original method
function populateDropdown(element, data) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].ID + '>' + data[i].Name + '</option>');
}
This works if a given array of objects has the field ID and Name. What I'm trying to achieve is something like this
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i].valueField + '>' + data[i].dataField + '</option>');
}
When I've tried calling this method like this I get Undefined as a result: populateDropdown($('#myDropdown'), dataArray, "ID", "DataType");
And when I've tried without the "" I get a console error saying that ID and DataType isn't defined. Is there a way to tell my method what fields I want from the object?
Use bracket notation -
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Note - to make this a little more resilient to special characters in the property values, I would do this instead:
$('<option />', { value : data[i][valueField] }).text(data[i][dataField]).appendTo(element);
You can do data[i][valueField]and data[i][dataField]:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Use bracket notation [] to access the properties:
function populateDropdown(element, data, valueField, dataField) {
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
What the others said, not sure if this is helpful, just fyi you can also define default values if you don't pass them like so...
function populateDropdown(element, data, valueField, dataField) {
valueField = valueField || 'some_default_value';
dataField = dataField || 'some_default_value';
for (var i = 0; i < data.length; i++)
element.append('<option value=' + data[i][valueField] + '>' + data[i][dataField] + '</option>');
}
Then you can call it like this, leaving valueField and dataField params out:
populateDropdown('someElement', 'someValue');

Using append() doesn't replace previous content

Firstly, I was trying to replace some contents in a div container using html() in Javascript on click. The problem using this approach is it only put the last value in the array.
So, I used append() instead. But it doesn't work like what I have expected. Well, it does append text in the for loops, but after a click, it just appends the content without removing the previous content like what html() does.
Here is how I implement it:
<div id="events-content"></div>
// using Responsive Calendar js
onMonthChange: function(events) {
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},
...
How do I replace the previous appended text using Javascript?
I'm using this in Responsive Calendar JS
well, you could do something like this...
Prepare all the markup in the loop.
var html = "";
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
html += '<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>';
}
$('#events-content').html(html);
Clear the html before the for loop/append mechanism.
Use .empty()
onMonthChange: function(events) {
$('#events-content').empty() //or $('#events-content').html('');
for (var eventsDate in options.events) {
if (eventsDate.indexOf(monthKey) != -1) {
var monthEvents = options.events[eventsDate];
for(i = 0; i < options.events[eventsDate].dayEvents.length; i++) {
$('#events-content').append(
'<p><b>' + eventsDate + ':</b> ' +
monthEvents.dayEvents[i].name + '<br/></p>');
}
}
}
},

How to dynamically access values in a json with jquery

Yes there are a number of threads questioning similar issues to the following, but I found very few and very little help regarding dynamic keys and pulling single values from jsons holding multiple values per key.
I have a json in which the keys are dynamic and I need to be able to call upon each separate value.
Any ideas?
json example below:
{"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}}
I have played around with the following code, but currently only managed to spit out a string of values rather than individual ones:
$.each(data, function (key1, value1) {
$.each(value1, function (key, value) {
$('body').append('<li id="' + key + '">' + key1 +' ' + key +' ' + value + '</li>');
});
});
Solved with this:
json = JSON.parse(data);
for (var index in json) {
$.each(json[index], function(key,value) {
for(var i = 0; i< json[index][key].length; i++){
$('body').append('<li>' + index +' ' + key +' ' + json[index][key][i] + '</li>');
}
});
}
JSON returns an object in JavaScript. So you could do something like this:
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
console.log("id"+i+": "+json.AppliedPrepaidBundle.id[i]);
}
This prints out all the values of the ID object: 14, 15, 24, 25, etc
Use JSON.parse to create an object. (See How to parse JSON in JavaScript). Then loop through the properties with for (x in yourObject) { ... }.
var jsonObject = JSON.parse('your JSON-String');
for (property in jsonObject) {
// do something with jsonObject[property]
console.log(property + ' ' + jsonObject[property]);
}
you can work with the javascript basic functionality:
http://jsfiddle.net/taUng/
var data = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var dataIndex in data) {
console.log(dataIndex, data[dataIndex]);
var subData = data[dataIndex];
for (var subDataIndex in subData) {
console.log(subDataIndex, subData[subDataIndex]);
}
}
And so on...
When your a fit in javascript you can also work with Recursion to don't repeat yourself. (http://en.wikipedia.org/wiki/Dont_repeat_yourself)
From this example you can access all elements
var json = {"AppliedPrepaidBundle":{"id":["14","15","24","25","26","27","28","29","30","31"],"prepaid_bundle_id":["5","5","5","5","5","5","5","5","5","5"]},"Device":{"id":["77","77","91","91","117","117","117","117","117","124"]}};
for (var i=0; i<json.AppliedPrepaidBundle.id.length; i++) {
$('body').append("<li>AppliedPrepaidBundle id"+i+": "+json.AppliedPrepaidBundle.id[i]+'</li>');
}
for (var i=0; i<json.AppliedPrepaidBundle.prepaid_bundle_id.length; i++) {
$('body').append("<li>PrepaidBundleid"+i+":"+json.AppliedPrepaidBundle.prepaid_bundle_id[i]+'</li>');
}
for (var i=0; i<json.Device.id.length; i++) {
$('body').append("<li>Device id"+i+": "+json.Device.id[i]+'</li>');
}
Here is the fiddle

Using data attributes and jQuery how can I select elements by data attribute name AND data attribute value

I need to select elements by data attribute name AND data attribute value.
Something like (but obviously, it doesn't work)
for(var i=0; i<x.length; i++){
var y = $('.my-class').attr('data-id', i); //trying to select here
y.html('input' + i);
}
Have no idea how to achieve this, please help! :)
you can use attribute selector
var y = $('.my-class[data-id="' + i + '"]');
since the selector .my-class is repeated, you can cache it
var els = $('.my-class');
for(var i=0; i<x.length; i++){
var y = els.filter('[data-id="' + i + '"]'); //trying to select here
y.html('input' + i);
}
Demo: Fiddle

Javascript and JSON. Looping of sub array fails

I am trying to loop out a JSON object using Javascript (jQuery).
Each object in the array of the main JSON object got embedded arrays containing tags.
I want to loop trough all files in the main object and at the same time loop through the tags and output them together with the files. The object are parsed before looping.
This is the JSON object:
{
"result": [
{
"id": "4f26f21f09ab66c103000sd00e",
"file_url": "http://thefilesat.s3.amazonaws.com/81/0000/12.jpg",
"tags": [
"image",
"elephants"
]
},
{
"id": "4f2422c509ab668472000005",
"file_url": "http://thefilesat.s3.amazonaws.com/9d/0000/7.jpg",
"tags": [
"image",
"green",
"tree"
]
}
]
}
It tried this code but it does not work:
for (var i=0; i < parsed.result.length; i++) {
for (var j=0; j < parsed.result[i].tags.length; j++) {
tags = '<div class="tag">' + parsed.result[j].tags[j] + '</div>';
};
html = '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
$("#files").append(html);
};
Your problem is that inside the tags loop, you're using the = operator; which is overwriting the variable your assigning to in each iteration.
Instead, try something like this;
var html = '';
for (var i = 0; i < parsed.result.length; i++) {
var tags = '';
for (var j = 0; j < parsed.result[i].tags.length; j++) {
tags += '<div class="tag">' + parsed.result[i].tags[j] + '</div>';
};
html += '<div class="file""><img src="' + parsed.result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
};
$("#files").append(html);
You also had parsed.result[j].tags[j] rather than parsed.result[i].tags[j].
I've also pulled the appending to $('#files') to be outside the loop so it only happens once, to reduce the amount of DOM lookups and DOM manipulation (as this is slow (in relative terms)).
With:
parsed.result[j].tags[j]
I think you meant:
parsed.result[i].tags[j]
Also, tags = should be tags +=, or you'll just overwrite the previous tag.
You have a typo, the 3rd line must be:
tags = '<div class="tag">' + parsed.result[i].tags[j] + '</div>';
(use result[i] rather than j)
When you're handling objects and arrays it's very cheap to store an extra reference to the array:
var result = parsed.result; // new
for (var i=0; i < result.length; i++) {
var tags = result[i].tags; // new
for (var j = 0; j < tags.length; j++) {
tags += '<div class="tag">' + tags[j] + '</div>';
}
html = '<div class="file""><img src="' + result[i].file_url + '" /><div class="tags">' + tags + '</div></div>';
$("#files").append(html);
};
at which point the fact that you inadvertently included the index i twice in your innermost dereference becomes impossible.
This actually performs better too, since the interpreter doesn't have to repeatedly dereference the entire chain of properties over and over.
FWIW, a cleaner jQuery way of writing this without using the .html() method would be:
var result = parsed.result; // new
for (var i=0; i < result.length; i++) {
var div = $('<div>', {'class': 'file'})
.append('<img>', {src: result[i].file_url });
var tags = result[i].tags; // new
for (var j = 0; j < tags.length; j++) {
$('<div>', {'class': 'tag', text: tags[j]}).appendTo(div);
}
$("#files").append(div);
};
which avoids all of the string concatenation, and quote mark escaping, and ensures that any HTML special characters in your tags are correctly escaped, etc.

Categories

Resources