I have a function that checks for a div, and if it exists it fills it with the matching data from a JSON array. The Div and the data have the same id & key, so I want to be able to put those in a string for a more elegant solution. However, the final element of trying to apply the string element to the data key doesn't seem to be working. I get "Cannot read property '0' of undefined"
Original code:
$.getJSON('myDataUrl', function(data) {
if ($("#title").length){document.getElementById("title").innerHTML=data.title};
if ($("#noun").length){document.getElementById("noun").innerHTML=data.noun};
if ($("#_id").length){document.getElementById("_id").innerHTML=data._id};
if ($("#owner_id").length){document.getElementById("owner_id").innerHTML=data.owner_id};
});
The more 'elegant' solution I'm trying to reach:
$.getJSON('myDataUrl', function(data) {
var contentString = "name,noun,_id,owner_id";
var splitContent;
splitContent = contentString.split(",");
for(i = 0; i < splitContent.length; i++)
{if ($("#" + splitContent[i]).length){
document.getElementById(splitContent[i]).innerHTML=data.splitContent[i];
};
}
Looks like should be enough:
$.getJSON('myDataUrl', function (data) {
for (var k in data) {
$("#" + k).html(data[k]);
}
});
The problem is data.splitContent[i]. That should be data[splitContent[i]]. That is, you want to use the current key (e.g. name) as a key in the data object.
You could also use jQuery's Map.
$.map(data, function(value, key) {
$("#" + key).html(value);
});
Here's the working JSBin : http://jsbin.com/tocege/2/edit?html,js,output
Related
$("#btnSubmit").click($('#form1 input'), function() {
var data = new Object();
for (var i =1; i < form1.length-1; i++) {
data[i] = form1[i].name + ":" + form1[i].value ;
}
document.write(JSON.stringify(data));
How to avoid view state and how to get string json output?
$("#btnSubmit").click($('#form1 input'), function() {
var data = [];
for (var prop in form1) {
data.push(form1[prop]);
}
document.write(data);
});
jsfiddle
An easy way to select only desired input elements is, to put a class on them then select elements based on that class. $('#form1 input.post').each(...)
Another way is to select all input elements and keep a not selector for those which you want to exclude.
To parse array back from json string you can use $.parseJSON(jsonString)
You can see the sample fiddle here.
I am new to localStorage. I set array in localstorage so how can get this value. My code as below.
$scope.lineItemID = data.id;
var itemtemp={
"itemid": data.id,
"qty": $scope.quantity
};
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
itemqty.push(itemtemp);
localStorage.setItem("itemqty", JSON.stringify(itemqty));
So my question is how can I get itemqty.qty as per itemid from localstorage
try Below code
$.each(data.itemqty, function(index, item) {
// append data using html //use item.name
});
OR try below
$.each(data, function(idx, item){
// append data using html
//
});
You are quite simply creating an array of objects itemqty and saving it in the browser's storage. When you do this:
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
//itemqty is available to you as an array of objects.
Suppose you are looking for the associated quantity for some itemid stored in the variable foo. You just need to traverse the parsed itemqty like so:
$.each(itemqty, function( index, value ) {
if(value.itemid == foo)
{
console.log(value.qty);
// value.qty is the required quantity
}
});
items=JSON.parse(localStorage.getItem('itemqty'));
for (var i = 0; i < items.length; i++) {
if(items[i].itemid === itmId) {
return items[i].qty;
}
}
I am using it & it's working
I am trying to use an array as a key value type scenario and it is working with the exception that every value starts with 'undefined'. I believe this is due to the initial assignment being a += operator however I am not sure how to resolve it.
This is the code stripped of a lot of string concats....
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] += 'item:'+item.ID;
});
Basically I am trying to append the string to the appropriate key....
You can change the code to only append the ID if there's already IDs:
var phasehtml = {};
$.each(json, function (i, item) {
// Use the existing value for the phase, or an empty string that we can append to
var existingValue = (phasehtml.hasOwnProperty(item.Phase) ? phasehtml[item.Phase] : "");
phasehtml[item.Phase] = existingValue + 'item:' + item.ID;
});
That's assuming that you want phasehtml to contain an appended lists of the form "item:1item:2" for each phase.
The array you have posted is empty.
var phasehtml = {};
It seems that is the cause the following statement
phasehtml[item.Phase]
is being evaluated to "undefined".
Hmmm,
got the problem.
In your code you are trying to add with that value which is previously not defined that's why this error is occur.
In your code you have not initialize the variable that you are adding.
So try this:
var phasehtml = {};
$.each(json, function (i, item) {
phasehtml[item.Phase] = "";
phasehtml[item.Phase] += 'item:'+item.ID;
});
In this first assign some value, here is blank and then use that index of array.
How can I get a value of data attribute by part of name?
For example:
<div data-pcp-email="some text" data-pcp-order="some int" data-ref="some data"></div>
And suppose, I want to get all data attributes begin with data-pcp-: the result must bedata-pcp-email and data-pcp-order
You can get all the attributes (and their values) where the attribute name beings with 'pcp' like below:
// get an object map containing all data attributes
var data = $('selector').data();
// filter out what you need
for(var key in data) {
if(key.indexOf('pcp') === 0) { // attrib names begins with 'pcp' ?
console.log(key + ' => ' + data[key]);
}
}
Here's a demo: http://jsfiddle.net/8waUn/1/
If you only set the attribute with the HTML or with jQuery attr function:
$('div[data^=pcp-]')
If you set the value with jQuery's data function, you will have to use filter.
$('div').filter(function(){
var data = $(this).data();
for (var key in data){
return key.indexOf('pcp-') === 0;
}
});
If you want only the attributes you can use map:
var values = $('div').map(function () {
var data = $(this).data();
var results = [];
for (var key in data) {
if (key.indexOf('pcp') === 0) results.push({
key: key,
value: data[key]
});
}
if (results.length)
return results;
}).get();
console.log(JSON.stringify(values));
Live DEMO
Use the "attribute begins with" jQuery selector:
$('div[data^=pcp-]')
I am returning a List<> from a webservice as a List of JSON objects. I am trying to use a for loop to iterate through the list and grab the values out of the properties. This is a sample of the returning JSON:
{"d":[{"__type":"FluentWeb.DTO.EmployeeOrder",
"EmployeeName":"Janet Leverling",
"EmployeeTitle":"Sales Representative",
"RequiredDate":"\/Date(839224800000)\/",
"OrderedProducts":null}]}
So I am trying to extract the contents using something like this:
function PrintResults(result) {
for (var i = 0; i < result.length; i++) {
alert(result.employeename);
}
How should this be done?
Be careful, d is the list.
for (var i = 0; i < result.d.length; i++) {
alert(result.d[i].employeename);
}
had same problem today, Your topic helped me so here goes solution ;)
alert(result.d[0].EmployeeTitle);
It's close! Try this:
for (var prop in result) {
if (result.hasOwnProperty(prop)) {
alert(result[prop]);
}
}
Update:
If your result is truly is an array of one object, then you might have to do this:
for (var prop in result[0]) {
if (result[0].hasOwnProperty(prop)) {
alert(result[0][prop]);
}
}
Or if you want to loop through each result in the array if there are more, try:
for (var i = 0; i < results.length; i++) {
for (var prop in result[i]) {
if (result[i].hasOwnProperty(prop)) {
alert(result[i][prop]);
}
}
}
Here it is:
success:
function(data) {
$.each(data, function(i, item){
alert("Mine is " + i + "|" + item.title + "|" + item.key);
});
}
Sample JSON text:
{"title": "camp crowhouse",
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}
Since you are using jQuery, you might as well use the each method... Also, it seems like everything is a value of the property 'd' in this JS Object [Notation].
$.each(result.d,function(i) {
// In case there are several values in the array 'd'
$.each(this,function(j) {
// Apparently doesn't work...
alert(this.EmployeeName);
// What about this?
alert(result.d[i][j]['EmployeeName']);
// Or this?
alert(result.d[i][j].EmployeeName);
});
});
That should work. if not, then maybe you can give us a longer example of the JSON.
Edit: If none of this stuff works then I'm starting to think there might be something wrong with the syntax of your JSON.
var d = $.parseJSON(result.d);
for(var i =0;i<d.length;i++){
alert(d[i].EmployeeName);
}
This will work!
$(document).ready(function ()
{
$.ajax(
{
type: 'POST',
url: "/Home/MethodName",
success: function (data) {
//data is the string that the method returns in a json format, but in string
var jsonData = JSON.parse(data); //This converts the string to json
for (var i = 0; i < jsonData.length; i++) //The json object has lenght
{
var object = jsonData[i]; //You are in the current object
$('#olListId').append('<li class="someclass>' + object.Atributte + '</li>'); //now you access the property.
}
/* JSON EXAMPLE
[{ "Atributte": "value" },
{ "Atributte": "value" },
{ "Atributte": "value" }]
*/
}
});
});
The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.
I have the following call:
$('#select_box_id').change(function() {
var action = $('#my_form').attr('action');
$.get(action,{},function(response){
$.each(response.result,function(i) {
alert("key is: " + i + ", val is: " + response.result[i]);
});
}, 'json');
});
The structure coming back from the server look like:
{"result":{"1":"waterskiing","2":"canoeing","18":"windsurfing"}}