How Can I Populate Dropdown Select Element using getJSON - javascript

I want to populate dropdown select menu.
i need to get bankName and iINNo from this JSON
My JSON :
{"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Bank of India","iINNo":"607161","remarks":"","timestamp":"21/11/2016 16:00:00"},{"id":2,"activeFlag":1,"bankName":"Bank of India","details":"Bank of India","iINNo":"508505","remarks":"","timestamp":"21/11/2016 16:00:00"},],"statusCode":0}
My Javacript :
let dropdown = $('#Bank');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Select Bank</option>');
dropdown.prop('selectedIndex', 0);
const url = 'http://cors-anywhere.herokuapp.com/';
// Populate dropdown with list of provinces
$.getJSON(url, function (data) {
$.each(data, function (res, code) {
console.info(res);
console.info(code);
dropdown.append($('<option></option>').attr('value', value.iINNo).text(index.bankName));
})
});

The array with bank data is under the property data inside the JSON. So the trick is to loop over that property - right now you loop over the entire JSON response, including the status and message properties.
You will get the individual bank object as the second argument item and then you can access it's properties and append it to your dropdown:
$.each(data.data, function (index, item) {
console.info('Bank Data: ', item);
dropdown.append($('<option></option>').text(item.bankName));
});

This should work
const banks = document.getElementById('banks');
banks.innerHTML = '<option selected="true" disabled>Select Bank</option>';
fetch('https://cors-anywhere.herokuapp.com/http://www.allindiaapi.com/HMESEVAAEPS/GetBankDetails?tokenkey=KzhnBIUi1wuM97yizKJ07WB3YwPSykyX9CjB6C6O5LRyClZ9YZl9NcIk5f6Fjna4')
.then(response => response.json())
.then(response => {
if(response.status){
response.data.forEach(bank => {
const option = document.createElement('option');
option.value = bank.iINNo;
option.innerContent = bank.bankName;
});
}
});
<select id="banks"></select>

The issue is because the data you need is in the data property of the data object, so you need to loop over data.data. In addition the properties of each object will be in the second argument of the handler function, code in your example. For example code.bankName.
However it's worth noting that the code can be tidied, and also have its performance improved by using map() to build a single string of option elements which you append to the DOM only once. Try this:
let $dropdown = $('#Bank');
$dropdown.html('<option value="" disabled>Select Bank</option>').val('');
// AJAX commented for example only:
//$.getJSON(url, function(data) {
let data = {
"status": true,
"message": "Request Completed",
"data": [{
"id": 1,
"activeFlag": 1,
"bankName": "Union Bank of India",
"details": "Union Bank of India",
"iINNo": "607161",
"remarks": "",
"timestamp": "21/11/2016 16:00:00"
}, {
"id": 2,
"activeFlag": 1,
"bankName": "Bank of India",
"details": "Bank of India",
"iINNo": "508505",
"remarks": "",
"timestamp": "21/11/2016 16:00:00"
}, ],
"statusCode": 0
}
let html = data.data.map(bank => `<option value="${bank.iINNo}">${bank.bankName}</option>`);
$dropdown.append(html);
//});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Bank"></select>

Related

Creating custom dynamic JSON string

I am trying to achieve the following dynamic JSON string creation. I can produce the id part but don't how to produce the name part. Ids are from the list and name is from the textbox.
I tried a lot but nothing seems to work. I want to select both strings and text box should result as below.
{
"name": "GROUP-X1",
"objects": [{ // this part is needed as a complete string
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589948757"
}, {
"type": "Host",
"id": "0050569A-7800-0ed3-0000-008589945523"
}]
}
var output = createJSON1();
function createJSON1() {
var arr = $("#select1 > option").map((index, val) => ({
"type": "Host",
id: val.value
})).get();
return JSON.stringify(arr);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>
Your code already builds the objects array. As such, all you need to do is wrap the output within another object providing the name property which you can retrieve from the value of #srch-obj. Try this:
var output = createJSON1();
function createJSON1() {
let obj = {
name: $('#srch-obj').val(),
objects: $("#select1 > option").map((t, el) => ({
type: "Host",
id: el.value
})).get()
}
return JSON.stringify(obj);
}
console.log(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="text" id="srch-obj" value="GROUP-X1">
<select id="select1" multiple size="2" style="width: 480px">
<option>0050569A-7800-0ed3-0000-008589948757</option>
<option>0050569A-7800-0ed3-0000-008589945523</option>
</select>

Facing Issue in ajax

I am new to laravel and ajax... i want to show the state of the selected country in dropdown list but when i select the country from the dropdown list it get data from the laravel perfectly and get it in ajax also.. but it is not able to append the data in html option tag.. for more details i am attaching the code of ajax also...`
$("#country").change(function(e){
var countryid = $(this).val();
console.log("Change Event Happpened on id : "+ countryid);
$.ajax({
type :"GET",
url :"GetStates/"+countryid,
success : function(statelist){
$("#state").empty();
$("#state").append('<option> Select State...</option>')
$.each(statelist,function (statename,stateid) {
**$("#state").append('<option>' + statename + ' </option>') // This line of code is not working**
console.log("in each function");
});
}
});
})
`
You're using jQuery.each function wrongly. jQuery.each callback function accepts two arguments:
Function( Integer indexInArray, Object value )
So according to your (wrong) code:
$.each(statelist,function (statename,stateid)
statename holds index of item and stateid receives statelist item, which clearly is against your idea.
Assuming that statelist has the following structure:
statelist = [
{
statename: 'LA',
stateid: 1
}
]
callback function should look like the following:
$.each(statelist,function (index, state) {
$("#state").append(`<option value="${state.stateid}">${state.statename}</option>`)
});
You can use javascript object destructuring to make this simpler:
$.each(statelist,function (index, {stateid, statename}) {
$("#state").append(`<option value="${stateid}">${statename}</option>`)
});
Working code:
const statelist = [{
statename: "LA",
stateid: 1
},
{
statename: "MA",
stateid: 2
},
];
$("#state").empty();
$("#state").append("<option value=''>Please select a state...</option>");
$.each(statelist, (index, {
statename,
stateid
}) => {
$("#state").append(`<option value="${stateid}">${statename}</option>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="state">
<option>This will be removed</option>
</select>

how to populate two <selects> via ajax with a json

I am making a system and I came across the following doubt .. I have two being the first to select the brand of the vehicle and the second would be to select the model of the vehicle. but I would like to select the brand of the vehicle and the of the model to load the models of the vehicles for the selected brand.
i have onde archive .json with brand and models of cars.
exemple format json
"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
<select id="brand"></select>
<select id="models"></select>
so I populate the first with the tags so the second would be populated with the models referring to the selected brand.
I need it when I select, for example BMW, the second select only the models referring to BMW, and not all models.
How do you do this?
thanks :)
I don't know enough about how the data is being fetched, but I believe you're asking about manipulating it in a way that makes it usable by the 2 selects. Take a look at the example below:
var json = [{
"value": "ACURA",
"title": "Acura",
"models": [{
"value": "CL_MODELS",
"title": "CL Models (4)"
}]
},
{
"value": "TOYOTA",
"title": "Toyota",
"models": [{
"value": "TOYOTA_MODELS",
"title": "Toyota Models (4)"
}]
}
];
$(document).ready(function() {
$('#models').prop('disabled', true);
$('#brand')
.append($("<option></option>")
.attr("value", "")
.text(""));
$.each(json, function(index) {
$('#brand')
.append($("<option></option>")
.attr("value", json[index]["value"])
.text(json[index]["title"]));
});
$('#brand').change(function() {
process($(this).children(":selected").html());
});
});
function process(brand) {
$('#models').prop('disabled', false).find('option')
.remove()
.end();
var models = $.map(json, function(entry) {
if (entry["title"] === brand) {
return entry["models"];
}
});
$.each(models, function(index) {
$('#models')
.append($("<option></option>")
.attr("value", models[index]["value"])
.text(models[index]["title"]));
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
//YOUR_JSON_DATA
//{"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
$.get( YOUR_JSON_DATA, function( data ) {
// Did you want data to be an array of brands?
for (let brand of data) {
$("#brand").append(`<option>${ brand.value }</option>`)
for (let models of brand.models) {
$("#models").append(`<option> ${ models.value } </option>`)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
Here is an example code snippet for ya. I hope it provides some clarity. Did you want the JSON data be an array?

jQuery's appendTo method causes "context is undefined" error

A page has two drop-downs which should be populated from a JSON array. When the array is processed it contains the option elements which need to be appended to the drop-downs. This task is granted to the jQuery's appendTo method which, however, causes an error to appear:
"TypeError: context is undefined".
Do you know why this is happening and how to fix it?
The source code is available below, as well on jsFiddle.
HTML:
<select id="ddlTypeNew">
<option value="">Select Type To Add</option>
</select>
<select id="ddlTypeEdit">
<option value="">Select Type To Edit</option>
</select>
JavaScript:
var json = $.parseJSON('[{ "MailTypeId": 1, "MailTypeName": "Register" }, { "MailTypeId": 2, "MailTypeName": "Login" }]');
json = json.map(function (obj) {
return $('<option>', { value: obj.MailTypeId, text: obj.MailTypeName });
});
$(json).slice().appendTo('#ddlTypeEdit');
$(json).appendTo($('#ddlTypeNew'));
You can do it like this:
var json = $.parseJSON('[{ "MailTypeId": 1, "MailTypeName": "Register" }, { "MailTypeId": 2, "MailTypeName": "Login" }]');
$.each(json,function (index,obj) {
$($('<option/>').val(obj["MailTypeId"]).html(obj["MailTypeName"])).appendTo('#ddlTypeEdit');
$($('<option/>').val(obj["MailTypeId"]).html(obj["MailTypeName"])).appendTo('#ddlTypeNew');
});
Map here actually returns a array of jQuery option objects. You need to loop through the array and then add them one by one to the dropdown like this:
var json = $.parseJSON('[{ "MailTypeId": 1, "MailTypeName": "Register" }, { "MailTypeId": 2, "MailTypeName": "Login" }]');
var arr = json.map(function (obj) {
return $('<option>', { value: obj.MailTypeId, text: obj.MailTypeName });
});
$.each(arr, function(i, n){
n.appendTo('#ddlTypeEdit');
})
OR JUST:-
$('#ddlTypeEdit').append(arr);

Why is jQuery each not going through all JSON items from two functions using $.when

The json returns from the two ajax functions seem to download complete when I check with Chrome Network inspector. However the jQuery each is not going through all items of both json files. It only goes through the first three items of the json files. So that jQuery each only builds the movie titles of the first three movies.
If I use $.when with only one function it works and returns all items.
I commented out the two areas that work as a single function.
jquery 1.11.0
Here is the javascript:
$(document).ready(function()
{
var movieCollectionUrl = 'json/movie_collection.json';
var movieFavoritesUrl = 'json/movie_favorites.json';
var movieCollectionElement = $('#collection ul');
var movieFavoritesElement = $('#favorites ul');
function getList(url)
{
return $.ajax(
{
dataType: "json",
type: "get",
url: url
});
}
function buildList(data, element)
{
$.each(data, function(i)
{
var title = data[0][i].title;
//var title = data[i].title; //this returns all items but only with a single function with $.when
var html = '<li>' + title + '</li>';
element.append(html);
});
}
function myExecute(movieCollectionData, movieFavoritesData)
{
buildList(movieCollectionData, movieCollectionElement);
buildList(movieFavoritesData, movieFavoritesElement);
}
/*
function executeSingle(movieFavoritesData)
{
buildList(movieFavoritesData, movieFavoritesElement);
}
*/
function myFail()
{
alert("FAILED TO LOAD");
}
$.when(getList(movieCollectionUrl), getList(movieFavoritesUrl)).then(myExecute, myFail);
//$.when(getList(movieFavoritesUrl)).then(executeSingle, myFail); //This one works. Using only one function here
}); //document ready
index.html
<!DOCTYPE HTML>
<head>
<title>Movies</title>
</head>
<body>
<div id="favorites">
<h2>Favorite Movies</h2>
<ul></ul>
</div>
<div id="collection">
<h2>Movie Collection</h2>
<ul></ul>
</div>
</body>
</html>
movie_collection.json
[
{
"title": "127 Hours",
"poster": "http://slurm.trakt.us/images/posters_movies/6646.1.jpg"
},
{
"title": "2012",
"poster": "http://slurm.trakt.us/images/posters_movies/463.jpg"
},
{
"title": "The 40 Year Old Virgin",
"poster": "http://slurm.trakt.us/images/posters_movies/658.1.jpg"
},
{
"title": "A Better Life",
"poster": "http://slurm.trakt.us/images/posters_movies/182444.1.jpg"
},
{
"title": "A Moment To Remember",
"poster": "http://slurm.trakt.us/images/posters_movies/162086.jpg"
}]
movie_favorites.json
[
{
"title": "A Seperation",
"poster": "http://slurm.trakt.us/images/posters_movies/176861.2.jpg"
},
{
"title": "Abraham Lincoln Vampire Hunter",
"poster": "http://slurm.trakt.us/images/posters_movies/184657.2.jpg"
},
{
"title": "The Adventures of Tin Tin",
"poster": "http://slurm.trakt.us/images/posters_movies/13066.2.jpg"
},
{
"title": "Agore",
"poster": "http://slurm.trakt.us/images/posters_movies/223.jpg"
}]
Have a look at the example of $.when in the documentation:
$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) {
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively.
// Each argument is an array with the following structure: [ data, statusText, jqXHR ]
var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It"
if ( /Whip It/.test( data ) ) {
alert( "We got what we came for!" );
}
});
As explained, the arguments passed to the callback function are arrays of the form [ data, statusText, jqXHR ]. The first element of the arrays contains the actual response. So you have to change your function to
function myExecute(movieCollectionData, movieFavoritesData)
{
buildList(movieCollectionData[0], movieCollectionElement);
buildList(movieFavoritesData[0], movieFavoritesElement);
}
The single case works because $.when doesn't create a new promise, it simply returns the one that $.ajax returns, so it doesn't aggregate the results of multiple promises.

Categories