JQuery: Populate HTML dropdown menu with JSON - javascript

I know this questions been asked before, I've read other posts and couldn't get it to work.
I'm trying to populate a drop down menu with JSON data but I'm having some issues, the drop down appears on my html page but theres nothing in the drop down, not even the "Please Select". Below is my code, do you see any problems with it.
HTML
<select id="dropDown">
</select>
JavaScript
$(document).ready(function () {
$.ajax({
url: 'http://localhost/api/Dynamic?database=',
dataType: 'Json',
success: function (results) {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
}
});
});
JSON
["Item1","Item2","Item3","Item4"]

Have you included jquery in your html head tag
Please also check your ajax is returning json data
I have make a fiddle and its working fine for me
$(document).ready(function() {
var $el = $("#dropDown");
var results = ["Item1","Item2","Item3","Item4"];
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
});
Here is working jsfiddle
https://jsfiddle.net/o5ju4kja/

var results = ["Item1","Item2","Item3","Item4"];
$(document).ready(function () {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDown">
</select>
As you can see, the jquery code works. The problem must be in your ajax request not responding the desired json.

The following code snippet is working fine so please verify the following points:
Verify that the request is working and you are receiving the correct answer.
Confirm that jQuery is added - probably it's missing
Verify that there is no error in console
var results = ["Item1","Item2","Item3","Item4"];
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDown">

Is it possible your JSON is not good encoding. Try to add a contentType format in your Ajax request:
$(document).ready(function () {
$.ajax({
url: 'http://localhost/api/Dynamic?database=',
dataType: 'Json',
contentType:"application/json; charset=ISO-8859-1",
cache:false,
success: function (results) {
var $el = $("#dropDown");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(results, function (index, value) {
$el.append($("<option></option>")
.attr("value", value).text(value));
});
}
});
});

Related

Chosen plug-in is not working when i create the element dynamically

Chosen plug-in is not working when i create the element dynamically
i created Select list dynamically from ajax response and the problem is Chosen plug-in not working with it , Please help me to solve it
here is my code:
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: '/Home/GetSubCategoriesByAjax',
type: 'GET',
datatype: 'Json',
data: { id: ID },
success: function (data) {
if (data.length > 0) {
console.log(data)
$("#SubListSelect").empty();
var $SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>');
$SubListSelect.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
$SubListSelect.append('<option value=' + value.SubCategoryId + '>' + value.SubCategoryName + '</option>');
});
$("#Div1").empty();
$("#Div1").append($SubListSelect);
}
else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
and and plugin code:
$(document).ready(function ($) {
$(function () {
$("#SubListSelect").chosen();
});
Thank you
My proposal:
in my demo I used a different url for the ajax and I figured out a possible HTML.
function GetSubCategories(ID) {
$.ajax({
cache: false,
url: "https://api.github.com/users",
type: 'GET',
dataType: "json",
data: { id: ID },
success: function (data) {
if (data.length > 0) {
var SubListSelect = $('<select id ="SubListSelect" class = "form-control"></select>')
.append('<option>Select Sub Category</option>');
$.each(data, function (i, value) {
SubListSelect.append('<option value=' + value.id + '>' + value.login + '</option>');
});
$("#Div1").empty().append(SubListSelect);
$("#Div1").find(SubListSelect).chosen()
} else {
}
},
error: function (r) {
alert('Error! Please try again.');
console.log(r);
}
});
}
$(document).ready(function ($) {
$("#SubListSelect").chosen();
$('#btn').on('click', function(e) {
GetSubCategories('1');
});
});
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<!--
The next two lines are the include files for chosen plugin
-->
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.jquery.min.js"></script>
<div id="Div1">
This is the starting div:
</div>
<button id="btn">Click Me To Create New chosen object into DIV</button>
I assume the select is in #Div1 which you are emptying, then re-appending.
in that case you need to re-initialize it:-
$("#Div1").empty();
$("#Div1").append($SubListSelect);
$("#SubListSelect").chosen();
A better option though would be to only empty the select and re-append the options to the select without emptying the #Div1. then call:-
$("#SubListSelect").trigger("chosen:updated");
also, this
$(document).ready(function ($) {
and this
$(function () {
mean the same thing, with the latter being short hand. Therefore you only need one.

How to use the each() function to iterate through a JSON file

I would like to show elements from a JSON file.
Here is the JSON file
"2015": {
"img": "<img src = \"../images/images/images_of_members/image1.jpg\">",
"img2": "<img src = \"../images/images/images_of_members/image2.jpg\">"},
"2016": {
"img": "<img src = \"../images/images/images_of_members/image1.jpg\">",
"img2": "<img src = \"../images/images/images_of_members/image2.jpg\">" }
Here is the JavaScript file
$.ajax("gallery.json", {
dataType: 'json',
success: function (response) {
$.each(response, function () {
$.each(this, function (i, el) {
$(".photo_target").css('display', 'block');
$(".photo_target").append(el);
});
});
}
});
Here is the HTML file
<div class="years">
<p data-year="2015">Pictures 1</p>
<p data-year="2016">Pictures 2</p>
</div>
<div class="photo_target"></div>
I would like to show only the pictures from the object 2015 if I click on the paragraph with attribute data-year 2015 and show pictures from object 2016 if I click on the paragraph with attribute data-year 2016. Now it is iterate through all objects and shows all pictures what can be found in this JSON file.
What should I change in the AJAX call to get it work as I want it?
Thank you
Long time I did some JQuery but you could do something similar to this:
First change your json like so*:
{2015 : ['/images/img1', '/images/img2'], 2016 : ['/images/img2']}
Then you do:
function fetchData(year) {
$.ajax("gallery.json", {
success : function(response) {
var images = response[year];
//images is now an array you could 'for each' over
images.forEach(function(image) {
//do your append...
})
}
})
}
(*Assuming you can change the json.)
Here's a working solution: https://jsfiddle.net/hgmx71zt/2/
Basically I grouped all images per year in a container div:
for (var year in jsondata) {
var $container = $("<div/>");
$container
.addClass("year-" + year)
.appendTo($photo_target)
.addClass("year-images");
for (var img in jsondata[year]) {
var $img = $(jsondata[year][img]);
$container.append($img);
}
}
I used CSS to make them hidden by default.
.year-images {
display: none;
}
Finally, I added a click event handler that toggles the ".visible" class which makes the given container visible (again using CSS)
$(".years").on("click", "[data-year]", function(e) {
var year = $(e.currentTarget).data("year"),
container = $photo_target.find(".year-" + year);
console.log(year);
console.dir(container);
container.toggleClass("visible").siblings().removeClass("visible");
});
The CSS for the visible class:
.year-images.visible {
display: block;
}
Try this:
$.ajax("gallery.json", {
dataType: 'json',
success: function (response) {
$(".photo_target").css('display', 'block');
for(var year in response){
for(var key2 in response[year]){
var $img = $(response[year][key2]);
$img.hide();
$img.data("year", year);
$(".photo_target").append($img);
}
}
}
});
$(".years p").click(function(){
var year = $(this).data("year");
$(".photo_target").find("img").hide();
$(".photo_target").find("img[data-year='" + year + "']").show();
return false;
});
$(function () {
$('.years p').on('click', function () {
$(".photo_target").children().remove();
var attr = $(this).attr('data-year');
if (typeof attr !== typeof undefined && attr !== false) {
var number = $(this).data('year');
console.log(number);
$.ajax("gallery.json", {
dataType: 'json',
success: function (response) {
$.each(response[number], function (i, el) {
$(".photo_target").css('display', 'block');
$(".photo_target").append(el);
});
}
})
}
})});
Here is my solution.
I have changed this line
success: function (response) {
$.each(response, function () {
$.each(this, function (i, el) {
$(".photo_target").css('display', 'block');
$(".photo_target").append(el);
to this
success: function (response) {
$.each(response[number], function (i, el) {
$(".photo_target").css('display', 'block');
$(".photo_target").append(el);
It works fine now.
Thank you for all your help.

Binding dropdown list using ajax and jQuery

I would like to bind the data from splunk to a dropdown list.
The servlet return a JsonString by gson
Gson gson = new Gson();
String jsonString = gson.toJson(arrays);
resp.getWriter().write(jsonString);
In the jsp, ajax was used to get back the jsonString and blind in drop down list.
$(document).ready(function() {
$.ajax({
type: "POST",
dataType : "json",
url : "../getName",
success : function(data) {
console.log("success to return name");
if (msg) {
alert("Somebody" + name + " was added in list !");
location.reload(true);
} else {
alert("Cannot add to list !");
}
$.each(objdata["wlsDomain"], function(i, val) {
jQuery('#DropdownList').append('<option value="' + val.name + '</option>');
});
};
)};
)];
It said $(...).ready is not a function. If I change the "$" to "jQuery", then there is no warning. However, binding is failed.
Then I have also tried the below code for knowing whether the ajax is workable.
And it showed "Fail". Therefore, the ajax is not workable.
jQuery(document).ready(function() {
var promise =jQuery.ajax({
type: "POST",
url: "../getName",
dataType: "json"
});
promise.fail( function() {
window.alert("Fail!");
});
promise.done( function() {
window.alert("Success!");
});
May I know what's wrong with this?
And how can I bind the name get from splunk to a dropdown list?
Thanks!
Try the following code:
$(document).ready(function () {
var $el = $('#DropdownList');
var url = "../getName";
$.getJSON(url, {}, function (data) {
$el.empty(); // remove old options
$.each(data, function(index, obj) {
$el.append($("<option></option>")
.attr("value", obj.name).text(obj.name));
});
} );
});

jQuery document ready call sequence

I have a following problem with jQuery. I use this code:
function populate_select_from_json(select, json_url) {
select.empty();
$.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo(select);
});
});
select.children(":first").attr("selected", true);
}
$(document).ready(function() {
var value_type = $("#value_type");
populate_select_from_json(value_type, SOME_URL);
var unit = $("#unit");
populate_select_from_json(unit, ANOTHER_URL + value_type.val());
});
I wanted to:
Load the document
Get some JSON data from an associated database
Put the data in #value_type <select> item
Get the value of #value_type select, and query the database once again to populate another select item.
The problem is, when I call value_type.val(), it always outputs null, even though the #value_type <select> is correctly populated. What am I doing wrong here?
I suppose something like this may work better with promises.
Along these lines (untested):
var populate_select_from_json = function($select, json_url) {
$select.empty();
return $.getJSON(json_url, function(data) {
$.each(data, function(key, value) {
$("<option></option>")
.attr("value", value.name)
.text(value.title)
.appendTo($select);
});
$select.children(":first").attr("selected", true);
});
};
$(document).ready(function() {
var $value_type = $("#value_type");
var $unit = $("#unit");
populate_select_from_json($value_type, SOME_URL).done(function(){
populate_select_from_json($unit, ANOTHER_URL + $value_type.val());
});
});

Jquery UI autocomplete results from JSON file

I am having great difficulty in successfully parsing a JSON file to use within JQuery UI autocomplete
Please see my dev page: http://www.zyredesign.com/autocomplete
The JSON isn't organised as well as I would have hoped as the items keys are ID's eg:
{"140":"Abarth",
"375":"Acura"
}
Etc....
Here is my javascript attempt:
$(document).ready(function() {
$('#cars').autocomplete({
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
alert( cars_array);
return cars_array;
})
},
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});
});
/*
function get_json()
{
var items = new Array();
$.getJSON('json.json', function(data) {
var items = [];
alert( eval ("(" + data + ")") );
// $.each(data, function(key, val) {
//items.push('<li id="' + key + '">' + val + '</li>');
// });
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
return items;
}
*/
Any help would be greatly appreciated, thanks!
The function you've supplied for the source: attribute doesn't return a value. The $.get() function does, but that won't reach the source attribute.
source: function()
{
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
return cars_array;
})
//You need to return something here
}
Also, it may be an issue that you're using an asynchronous call to the json file in a synchronous pattern. In other words, consider this:
$.getJSON('json.json', function(data)
{
cars_array = new Array();
$.each(data, function(k, v) {
cars_array.push(v);
})
//Now you definitely have the cars so you can do the autocomplete
$('#cars').autocomplete({
source:cars_array,
minLength: 3,
focus: function( event, ui ) {},
select: function( event, ui ) {
$('#suggestions').html(ui);
return false;
}
});

Categories

Resources