Can't get JSON to render correctly in dropdown - javascript

I'm trying to take JSON from a PHP file and use it to populate a dropdown box.
I'm getting the JSON just fine from the PHP file. It looks like this:
[{"state":"AL"},{"state":"AK"},{"state":"AZ"},{"state":"AR"}]
I can see in the response in developer tools that it's coming over fine. However, when I look at the JSON, line 1 is empty and everything is on line 2. Not sure if that's a problem or not.
On the HTML side, here's what I've got:
<select id="myselect"></select>
and
$.getJSON('state_get.php', function(data) {
$.each(data, function(key, val) {
$('#myselect').append("<option>"+key.text+"</option>");
})
});
What I get in my dropdowns are a bunch of options with "undefined". There appear to be one for each JSON value, so something's party right, but not all the way.
Any help would be appreciated.

The first argument to each callback is the index, second is the value also the key to the property is State not text
$.getJSON('state_get.php', function (data) {
$.each(data, function (key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
})
});

First argument of $.each when looping an array is index, the second is the element of the array
Try
$('#myselect').append("<option>"+val.state+"</option>");
Each of the objects in your array would be an element
reference jQuery.each() API Docs

You object has property state, not text
$.each(data, function(key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
});

Try this
$('#myselect').append("<option>"+val.state+"</option>");

Lets have dropdown like below
<select id="myselect" name="stateList" class="state-list ></select>
You can append your value like this
var stateSelector = $('select.state-list');
var option = $("<option value=''></option>");
$.each(data, function(key, val) {
option = $("<option value='" + val.state + "'>" + val.state + "</option>");
stateSelector.append(option);
});
$('.state-list').selectpicker('refresh'); // you can refresh your dropdown if required

Related

Dropdown list filled with undefined

I have a stored procedure which gets data from the database and I populate a dropdown list with that data. The problems is, I have a lot of undefined values in the dropdown. The correct data comes back and is successfully inserted in the dropdown but somehow I have a lot of undefined rows inserted in the dropdown as well.
var url = window.rootUrl + 'DUP/GetAllStreets';
$.getJSON(url, function (streets) {
console.log("streets", streets)
$("#streetNameID").append('<option></option>');
$.each(streets, function (index, value) {
$("#streetNameID").append('<option value="' + value.Ime_1251 + '">' + value.Ime_1251 + '</option>');
});
});
This is my function. I print the street out in the console, no undefined rows there. I am not sure what's causing this. Basically half of the rows are undefined

jQuery .each() prints only last value from json

I have an issue with jQuery.each(). I retrieve json data from another php file then I want to print specific key from it.
here is the js :
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson,function(data){
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael Great","first_name":"Michael","last_name":"Great"},
{"id":"100000251643877","name":"George Pambudi","first_name":"George","last_name":"Pambudi"}]
I want to print all of name from the json, but it print only last name key of the json. I have tried to use .html() and it also returns only last name key. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You are emptying the div first and then appending :
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
Instead just use :
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
Don't empty it in the loop if you don't want to keep only the last data. Change your callback to
jQuery("#fetchmember").empty();
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
});
Note that you can make one append if you want :
jQuery("#fetchmember").html(data.map(function(item){
return '<li>'+item.name+'</li>'
}).join(''));

Parse JSON field names and values

I've looked half a day for a solution to this, but nothing seems to work. I want to use jQuery to load JSON from a file that essentially looks like this:
[{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"},
{"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"},
{"field_a":"3","field_b":"3000","field_c":" BONDS"},
{"field_a":"4","field_b":"4000","field_c":" STOCKS"}]
What I want to do is parse the JSON to dynamically populate input fields, so something like (please note that ??field?? and ??field value?? is what I need to know):
<input id="field_a" name="field_a" value="">
<input id="field_b" name="field_b" value="">
<input id="field_c" name="field_c" value="">
<script type="text/javascript">
$(function(){
//GET THE JSON DATA
$.getJSON('../coreScripts/selectGeneralLedger.php', function(data) {
//PARSE TO FIELDS
$.each(data, function(index) {
$("#"+data[index].??field name??).attr("value", data[index].??field value??);
}) //END PARSE
}); //End get JSON
});
</script>
I know how to access the field values manually using data[index].field_a, but can't for the life of me figure out how to parse this dynamically. Any help would be appreciated.
UPDATE*
adeneo gave me the solution below in the comments. Simple. Here's the script:
var data = [{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"}, {"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"}, {"field_a":"3","field_b":"3000","field_c":" BONDS"}, {"field_a":"4","field_b":"4000","field_c":" STOCKS"}];
$.each(data, function(index, obj) {
$.each(obj, function(key, value) {
$('<input />', {id: key, name:key, value:value}).appendTo('body');
});
});
If i'm not understand you, it can be an answer.
$.each(data, function(index) {
$.each(data[index] ,function(key,value){
console.log("key :" + key + " value :" + value );
})
}) //END PARSE
key variable is the answer what you request for.

Show enter contents of JSON

QUESTION ::
I know this is a redundant question, but I am finding little help in other similar questions...
I have a json file.
I can load the json fine, but when I try to output a specific element with this
div.innerHTML = jsonfromfile[element];
I only get this...
[object Object]
as my output...
How do I get the entire element to display instead of this [object Object]?
more code to get a feel for how it is being done up...
var activity;
function jsfr() {
$.getJSON('myjson.json', function(response){
jsonfromfile = response;
})
}
.
.
.
SOLUTION :: from Francis Stalin's answer
I added a new function...
var items;
function outty(data) {
$.each(data, function(key, val) {
items=items+key+","+val+";";
});
}
and i set the depth on the json leaving me with an object which i send to outty...
dpth = jsonfromfile["elementOne"]["elSubone"]["elsuboneSub"];
outty(dpth);
div.innerHTML=items;
here's the HTML that shows the div it all prints to...
<div class="col-rght">
<div class="text" id="postcomp"></div>
</div> <!--div class="col-rght"-->
this turns the object of your desired json depth into an ugly string that you can then format for display..
if you like html lists check out how Stalin did it, but be weary of his appendTo('div')... this will place your list in every div. Try putting the name of the class of the div you want to print to with a period leading it, appendTo('.outputbox')
you can't append the json object directly into ur html. u have to parse and convert into string
$.getJSON('myjson.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('div');
});
http://api.jquery.com/jQuery.getJSON/
Use JSON.stringify(yourjsonobjecthere)
Try div.innerHTML = JSON.stringify(jsonfromfile[element]);

An unwanted object in the last cell of an array

I'm using the following code on a parsed XML array:
$(this).find("cp_group").each(function() {
$("select#comp_1").append('<optgroup label="' + $(this).attr('label') + '"><option>' + $(this).find("cmp").map(function() {
return $(this).text();
}).get().join("</option><option>") + $(this).append('</option></optgroup>'));
});​
And i get an unwanted [object Object] in the last option of each option group as following:
<select name="comp_1" id="comp_1">
<optgroup label="Combat">
<option>Arme</option>
<option>Arts martiaux</option>
<option>Esquive</option>
<option>Feinte</option>
<option>Parade</option>
<option>Lutte[object Object]</option>
I dont understand from where this [object Object] come from and I didn't achieve to not get it or to remove it.
Thanks for you help.
It's coming from the + $(this).append(...). You just want the +'</option....' part, without that jQuery wrapper.
You've misunderstood how jQuery, and in particular append, works. When you're manipulating things with jQuery, you're not dealing with markup (largely), you're dealing with objects (DOM elements).
This should fix it:
$(this).find("cp_group").each(function() {
// Get this entry
var $this = $(this);
// Create the optgroup
var optgroup = $('<optgroup label="' + $this.attr('label') + '">');
// Fill it in
$this.find("cmp").each(function() {
$("<option>").text($(this).text()).appendTo(optgroup);
});
// Append it to the select
$("select#comp_1").append(optgroup);
});​

Categories

Resources