traversing jQuery JSON Object array - javascript

I am try access an Object array using getJson, I've tried many things but I keep getting an 'undefined' or [Object, object] returned.
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Here is the JSON, I am trying to get the 'title' of each 'entries'.
{
"$xmlns": {
"pl1": "url"
},
"startIndex": 1,
"author": "MJS",
"entries": [
{
"title": "This is target",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
},
{
"title": "title2",
"m$ct": [
{
"m$name": "name"
}
],
"m$rt": "pd",
"m$content": [
{
"plfile$width": 640
},
{
"plfile$width": 960
}
],
"plm$c": [],
"link": ""
}
]
}

$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.entries.title + "</li>" );
});
should instead read:
$.each( data.entries, function( key, entry ) {
items.push( "<li id='" + key + "'>" + entry.title + "</li>" );
});

You're iterating over the whole json instead of the entries
It should be data.entries in the each and then just val.title
$.getJSON( "js/test.json", function( data ) {
var items = new Array();
$.each( data.entries, function( key, val ) {
items.push( "<li id='" + key + "'>" + val.title + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});

Related

how to remove other row based on selected row value?

i try to remove all row that has not equal to "acctname" and once I click 1 row nothing happen ? im using check box and function to get the value of selected row.
var TableExcess;
$(function () {
TableExcess = $('#PaymentExcess').DataTable({
"scrollY": '50vh',
"scrollCollapse": true,
"paging": false,
//"searching": false,
"ajax": "#Url.Action("GetPaymentExcess", "payable")",
"columns": [
{
"render": function (data, type, full, meta) {
return "<input type='checkbox' class='checkbox' onclick='addavailable(" + full.Id + ", " + full.AvailableAmount + ", \"" + full.AccountName + "\", this.checked)'>"
}
},
{ "data": "Id" },
{ "data": "AccountName" },
{ "data": "PaidAmount" },
{ "data": "AvailableAmount" },
]
});
});
function addavailable(id, amount, acctname, isChecked)
{
var filteredData = TableExcess
.column( 2 )
.data()
.filter( function ( value, index ) {
return TableExcess.row(value).data()[2] != acctname;
})
TableExcess.rows( filteredData )
.remove()
.draw();
}

Syntax error: Missing ; Before Statement

I am getting a syntax error on seemingly fine code, also the error does not make sense so that indicates there is some foul play. However, I cannot seem to pinpoint it. On the first line, "aoColumns: [" it states that there is a missing semi-colon before statement. Here is the code in question:
<script type="text/javascript">
"aoColumns": [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
]
"fnCreatedRow": function(nRow, aData, iDataIndex) {
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e){
$.get('/files?path='+ path).then(function(data){
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
});
e.preventDefault();
});
};
</script>
What you have looks like the content of an object initializer, but without the beginning and end of one. For instance, this is valid:
var object = {
"aoColumns": [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
],
"fnCreatedRow": function(nRow, aData, iDataIndex) {
if (!aData.IsDirectory) return;
var path = aData.Path;
$(nRow).bind("click", function(e){
$.get('/files?path='+ path).then(function(data){
table.fnClearTable();
table.fnAddData(data);
currentPath = path;
});
e.preventDefault();
});
}
};
The changes are:
Adding the var object = { at the top
Removing the ; from the }; that used to be at the end, making it just }
Adding a }; to close the object
Adding a , after the closing ] on the aoColumns array
var obj = {
"key": value
};
Where are your curly braces? You're just trying to define object keys without placing them on an object, so that is why you're getting the syntax error.
var my_object = {
"aoColumns": [
// code here
],
"fnCreatedRow": function(nRow, aData, iDataIndex) {
// function definition here
}
};
What you have there is not valid JavaScript syntax.
Assuming you want to assign an array to variable aoColumns, do the following:
var aoColumns = [
{ "sTitle": "", "mData": null, "bSortable": false, "sClass": "head0", "sWidth": "55px",
"render": function (data, type, row, meta) {
if (data.IsDirectory) {
return "<a href='#' target='_blank'><i class='fa fa-folder'></i> " + data.Name +"</a>";
} else {
return "<a href='/" + data.Path + "' target='_blank'><i class='fa " + getFileIcon(data.Ext) + "'></i> " + data.Name +"</a>";
}
}
}
]
Same thing for fnCreatedRow.
If you are trying to create a JavaScript object with the two elements mentioned above instead, take a look at the other answers.

How to remove one particular value in autocomplete?

$(document).on("click","#Id",function(){
var data = [
{ value: "AL", label: "Alabama" },
{ value: "AK", label: "Alaska" },
{ value: "AZ", label: "Arizona" },
{ value: "AR", label: "Arkansas" },
{ value: "UT", label: "Utah" },
{ value: "VT", label: "Vermont" },
{ value: "VA", label: "Virginia" },
{ value: "WI", label: "Wisconsin" },
{ value: "WY", label: "Wyoming" }
];
$("#Id").autocomplete({
minLength: 0,
source: data,
select: function( event, ui )
{
alert(ui.item.label);
},
})
.data("ui-autocomplete")._renderItem = function( ul, item )
{
if (item.label != "Virginia") {
return $( "<li>" )
.append( "<a>" + item.value + "<br>" + item.label + "</a>" )
.appendTo( ul );
}
};
});
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="test" id="Id">
This is my sample code if i use Virginia am getting empty line but i need the output to be blank.
can anyone solve my issue and provide me an solution
Try this:
$("#Id").data("ui-autocomplete")._renderItem = function( ul, item )
{
if(item.desc != "test"){
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
}
};
instead of uiAutocomplete use ui-autocomplete
Looking at the data on #Id. It looks like its stored under autocomplete.
so, if you have already called
$("#Id").autocomplete({
source: data,
etc : etc
});
then you can call:-
$("#Id").data('autocomplete')._renderItem = function(ul, item) {
if (item.value != "test") {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
}
};
or you can instantiate and set _renderItem like :-
$("#Id").autocomplete({
source: data
}).data('autocomplete')._renderItem = function(ul, item) {
if (item.value != "test") {
return $("<li>")
.append("<a>" + item.label + "<br>" + item.desc + "</a>")
.appendTo(ul);
}
};
UPDATE
It looks like different versions of jQueryUI store autocomplete under data differently, as your snippet compared to the version I used are different (autocomplete vs ui-autocomplete).
The issue with the empty line, is a border around the ul. Where the autocomplete thinks is has a value to show, but as you are saying not to render the only value in the autocomplete list then the ul still has the border. By removing the border around the ul will fix this. See the snippet below:-
var data = [{
value: "AL",
label: "Alabama"
}, {
value: "AK",
label: "Alaska"
}, {
value: "AZ",
label: "Arizona"
}, {
value: "AR",
label: "Arkansas"
}, {
value: "UT",
label: "Utah"
}, {
value: "VT",
label: "Vermont"
}, {
value: "VA",
label: "Virginia"
}, {
value: "WI",
label: "Wisconsin"
}, {
value: "WY",
label: "Wyoming"
}];
$("#Id").autocomplete({
minLength: 0,
source: data,
select: function(event, ui) {
alert(ui.item.label);
},
})
.data("ui-autocomplete")._renderItem = function(ul, item) {
if (item.label != "Virginia") {
return $("<li>")
.append("<a>" + item.value + "<br>" + item.label + "</a>")
.appendTo(ul);
}
};
.ui-autocomplete {
border: 0 !important;
}
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/ui-darkness/jquery-ui.min.css" rel="stylesheet">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<input type="test" id="Id">

Alter Ajax Json Query Parameter [duplicate]

This question already has answers here:
How do you pass multiple parameters of the same type to jQuery Get
(5 answers)
Closed 9 years ago.
This is my current code: http://jsfiddle.net/spadez/nHgMX/2/
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 7,
name_startsWith: request.term,
country: "UK"
},
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
},
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
This link states this: http://www.geonames.org/export/geonames-search.html
featureclass(es) (default= all feature classes); this parameter may
occur more than once, example: featureClass=P&featureClass=A
How can I adjust my code to set the feature class to A and P not just P as it is currently?
I find 2 solutions:
First one is use method suggested by #George Cummins:
jQuery.ajaxSettings.traditional = true;
...
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: ["A","P"],
In second you can add parameters to query string:
$.ajax({
url: "http://ws.geonames.org/searchJSON?featureClass=A&featureClass=P", // you can concantenate it

How to output data as HTML from JSON object using getJSON

Hello there I will try and keep this simple and short
I have a getJSON function that runs every 5 seconds. Now when I display the data using document.write function it dosent seem to want to update. The page is stuck in a loading loop. How can I get the data to display on my page? My JSON is fine but I will show you anyways.
<script type="text/javascript">
$.ajaxSetup ({
cache: false
});
setInterval(function(){ $.getJSON('names.json', function(data) {
for(i in data) {
document.write(data[i] + "<br/>");
}
});
},5000);
</script>
This is the JSON object
{
"one": "",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Don't actually use document.write. Once the page is loaded, that will erase the page. Use (jQuery's) DOM methods to manipulate the DOM.
$.getJSON('names.json', function(data){
for(var i in data){
$('#myDiv').append(data[i]);
}
});
I would recommend you use jQuery,
I used this to create a form from my json item, I hope this helps...
function jsonFormCreator(frmJSON)
{
var createdHTML = ""; var elementType, id;
console.log(JSON.stringify(frmJSON));
for(item in frmJSON)
{
formElement = frmJSON[item]; elementType = formElement.elementType; id = formElement.id;
if(elementType == "input")
{
createdHTML += "<input id='" + id +"'";
if(formElement.type == "checkbox")
{createdHTML += " type='" + formElement.type + "' checked='" + formElement.checked + "'";}
else{createdHTML += "type='" + formElement.type + "' value='" + formElement.value + "' onclick='" + formElement.onclick + "'";}
createdHTML += "/><br>"
}
else if(elementType == "textarea")
{createdHTML += "<textarea id='" + formElement.id + "' rows='" + formElement.rows + "' cols='" + formElement.cols + "' value='" + formElement.value + "'></textarea><br>";}
else if(elementType == "select")
{
var options = formElement.values;
createdHTML += "<select id='" + formElement.id+ "'>";
for(i = 0 ; i < options.length ; i++)
{createdHTML += "<option value='" + options[i][0] + "'>" + options[i][1] + "</option>";} //Adding each option
createdHTML+= "</select><br>";
}
}
console.log("Complete");console.log(createdHTML);
document.getElementById('mainContainer').innerHTML = createdHTML;//Adding to the DOM
}
And my JSON would look like this
{
"0": {
"elementType": "input",
"id": "frm1",
"type": "text",
"value": "form Liam",
"label": "Test Text Input"
},
"itemBTN": {
"elementType": "input",
"id": "frmAlert",
"type": "button",
"onclick" : "loader(homePage);",
"value": "Home Page",
"label": ""
},
"item2": {
"elementType": "textarea",
"id": "frm2",
"rows": 5,
"cols": 30,
"value": "helddddddddlo",
"label": "Test Textarea"
},
"item3": {
"elementType": "select",
"id": "frm3",
"values": [
[
"value1",
"Pick Me"
],
[
"value2",
"UserDis2"
],
[
"value3",
"UserDis3"
],
[
"value4",
"UserDis4"
],
[
"value5",
"UserDis5"
],
[
"value6",
"UserDis6"
]
],
"label": "Test Select"
},
"item4": {
"elementType": "input",
"id": "frm4",
"label": "Checkbox",
"type": "checkbox",
"checked": true
}
}
This code adds the form in to my div tag with the id mainContainer
I know its alot of code, but i hope it helps !
You want to render dom which will contain the data, then when you get the data update the dom.
As an exceedingly simple example, on your page have a container
<div id="one"></div>
and then in your ajax success handler
$("#one").text(json.one);
This uses jquery to grab the dom element with id "one", and update its text.

Categories