I am trying to access the country names from this json -
https://restcountries.eu/rest/v1/all
This is my code for loading that json -
<script>
(function() {
var country = "https://restcountries.eu/rest/v1/all";
$.getJSON( country)
.done(function( data ) {
$.each(data, function(key, value) {
$('#mySelect').empty();
$('#myselect').append('<option>' + data.name + '</option>');
});
});
})();
</script>
The problem may be in data.name statement. I couldn't find any solution on my own. Plus, i am new to JSON. Any help or at least any comment to point my faults will be appreciated.
it should be value.name, data is the array you get from the api, value is each item in the array. also, remove empty as it's remove everything in each loop cyle...
see working code here
Related
Note please. (I'm currently using the Spring Framework (MVC))
The value sent from Controller to ajax is ...
It looks like the picture above.
I am looping through the forEach statement for the values in that array, and I want to put the value into the tag.
So I wrote the code.
$(function()
{
$('#doctorSelect').change(function()
{
$('#selectGugan').show();
var doctor_idx = $(this).val();
$.ajax
({
type: 'POST',
url: 'selectDoctor.do',
data: {"d_idx":doctor_idx},
dataType: 'JSON',
success: function(sectionDate)
{
console.log(sectionDate);
var html = "<option value=''>Choice Doctor</option>";
var responseData = [];
responseData.push(sectionDate);
console.log(responseData);
$.each(responseData, function(key, value)
{
console.log("forEach statement in responseData :" + responseData);
//html+="<option value="+new_date+">"+new_date+"</option>";
});
$('#doctorSelect_2').html(html);
},
error: function(sectionDate)
{
console.log("data : " + sectionDate);
}
});
});
});
But unexpectedly, I do not get the key, value.
In fact, I don t know about the jquery forEach statement.
How do I set key, value?
I just want to bring those values and express it like this.
<option value="ri_idx">ri_startDate ~ ri_endDate</option>
How to set key, value or How to use jquery forEach statement ?
I am a beginner. I would appreciate it if you could give me an example.
In your case I am not sure why would you be doing this:
responseData.push(sectionData);
because this way you dont get an array of objects as I believe you thought you would, you simply will get an array with 1 element in it, which is many objects, so doing a forEach on that array will not help, because the value will be the multiobject element (not a single object that you could access properties).
What you want to do is iterate over your original objects, so your code should be something like this:
$.each(sectionDate, function(key, value){
// here you can access all the properties just by typing either value.propertyName or value["propertyName"]
// example: value.ri_idx; value.ri_startDate; value.ri_endDate;
});
Hope this helps!
In jQuery forEach working like this
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If you are using Array for loop than key is array index and value values and if you are using javascript object then object key is key and value is object value for the particular key.
You can read more at jQuery documentation.
Just use property names in object. Check if this helps
$(document).ready(function() {
var responseData = [
{startdate: '2017-12-21', enddate: '2017-12-22', idx: '1'},
{startdate: '2017-11-21', enddate: '2017-11-22', idx: '1'},
{startdate: '2017-10-21', enddate: '2017-10-22', idx: '1'}
];
var html = '';
$.each(responseData, function(key, value) {
html += "<option value=" + value.startdate + ">" + value.startdate + "</option>";
});
$('#doctorSelect').html(html);
});
I have a function that, taking a JSON array of objects, where each object has an id and a text field label (variable for each select), it populates the options.
The function I am trying to write is:
function populateSelect(urlString, id, tag){
$.getJSON(urlString, function(data){
$.each(data, function(){
$(id).append($("<option></option>").text(this.tag).val(this.id));
});
});
}
So this.id will always be true as every JSON obect will have an attribute where the key is 'id'. Yet this.tag is what I want to be variable as this can change for each type of JSON object/select I am building.
For example, two valid JSON objects I could be working with are:
[{id:'1', name:'John Doe'}, {id:2, name:'Jane Doe'}]
and
[{id:1, model:'Toyota'}, {id:2, model:'Honda'}]
Each of these JSON objects would be used to populate the <option> fields for the respective <select> element. Thus for the first JSON object if this was not a function to be used for many different Select elements, that line would read:
$.(id).append($("<option></option>").text(this.name).val(this.id));
and the second JSON object would have a line that read:
$.(id).append($("<option></option>").text(this.model).val(this.id));
Apologies if any of the jargon is incorrect, I'm coming up to speed with JQuery.
I think what you are looking for is this:
$.each( data, function( key, value ) {
//get all the properties of the object
var keys = Object.keys(value);
var option = document.createElement('option');
option.value = value.id;
//use the second property as inner html
option.innerHTML = value[keys[1]];
$("#mySelect").append(option);
});
http://jsfiddle.net/e55kW/1/
I updated the jsFiddle of #jmm
#Yoeri pointed out your typo with $.()
Is this fiddle what your trying to attempt?
I just created a string and appended it to the select element.
$.each( data, function( key, value ) {
var option = "<option value="+value.id +">"+ value.name + "</option>";
$("#mySelect").append(option);
});
Found out (prior to coming back and seeing Yoeri's also correct response) that this works:
function populateSelect(urlString, id, tag){
$.getJSON(urlString, function(data){
$.each(data, function(){
$(id).append($("<option></option>").text(this[tag]).val(this.id));
});
});
}
The difference from the above is that I changed this.tag to this[tag]
I am returning one JSON response from the server:
{'error':'true',fields:[[{'pk':2,'title':'test'}],{'votes':20,'cant':{1:0,2:3}}]}
Console Dev return
Object { error="true", fields=[2]}
I'm trying to get all the data fields[2], but not work, I'm doing something:
$.each(data.fields, function(i,item){
console.log(data.fields[i]);
})
Question: I know that I'm doing wrong, I want to access all the data in the order fields[2], pk and title.
Thanks.
You can fetch fields[2] using following:
$(data.fields).last()[0] // Give {votes: 20, cant: Object}
which you can use to iterate and get all data as:
var other_data = $(data.fields).last()[0]
$.each(other_data, function(key, value){
console.log('key : ' + key + ' value: ' + value);
});
Your code is need some corrections try this,
Demo
$.each(data.fields[1], function(i,item){
console.log(item);
})
I have a function that injects user's data into html file
the json format is something like this:
{"Fname":"abc","LName":"cdf", "Phone":"123456";}
this is a function to inject data into html file:
function injectData(data){
$.each(data, function(key, value) {
//notice that in the "data.value", I want 'value' to be a variable
//so that when I loop over the array, data.value will become data.Fname,
//and then data.LName and then data.Phone
$("#"+key).html(' ' + data.value +'');
});
How can I force javascript to interpret 'value' as a variable first before calling data.value in order to get the real value from JSON object? This is a little bit confusing. Hope you understand .Thank you
Write something like:
for(key in data){ $("#"+key).html(' ' + data[key] +''); });
Ok, Ive got a Java Servlet returning some JSON (In Application/JSON format). To do this, im using the GSON libary.
The Servlets GET method takes one paramater, ID. The servlet seems to be working, For example,chrome shows my AJAX GET request returning the following when the [Booking]ID paramater sent is 1.
0: {WidgetID:46, BookingID:1, X:393, Y:50, Content:Test1}
1: {WidgetID:47, BookingID:1, X:337, Y:251, Content:Test2}
2: {WidgetID:48, BookingID:1, X:97, Y:198, Content:Test3}
The problem I have is with parsing this response. Here is my JS code:
loadPositions() {
var BookingID =
if (BookingID != null && BookingID != "null")
{
var data = {"id" : BookingID};
$.getJSON("Widget", data, function(data) {
// Successfully got all this bookings widgets as JSON, TODO: Parse this!
});
}
}
What should I put in the "TODO: Parse this!" section?
I want to foreach over all the elements, and grab their data. I really suck at this JQuery stuff.
In the todo section, you should do the following to loop through all the arrays:
$.each(data, function(index,value){
// here index=0 & value.WidgetID=46, value.BookingId = 1, use it as you would like to.
})
Have a look at jQuery .each()
http://api.jquery.com/jQuery.each/
and for a good example of what you want to do...
http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.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('body');
});
Take a look at
https://github.com/acobley/jBoggyAppy/blob/HectorV2-Cassandra-0.7.0/WebContent/Scripts/index.js
the ShowScrollingTags function.