dynamically populate data in dropdown using javascript api using axois - javascript

it is a dropdown with top and other in the world
the cities and data will be dynamically populated in dropdown using javascript API using Axios
With external Apis.
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">---Top Cities---</option>
<option value="2">Mumbai</option>
<option value="3">Delhi</option>
<option value="1">Bengaluru</option>
<option value="2">Chennai</option>
<option value="3">Kolkata</option>
<option value="2">---Other Cities---</option>
<option value="3">Bhavnagar</option>
<option value="3">Udaipur</option>
<option value="3">Pune</option>
</select>
[
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
{ "id": "7", "name": "Kolkata", "state": "West Bengal" }
]

let options = [
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
{ "id": "7", "name": "Kolkata", "state": "West Bengal" }
]
const select = document.querySelector(".form-select");
options.map(val=>{
let opt = document.createElement("option");
opt.innerText = val.name
select.appendChild(opt);
})
Just add this in your javascript file .

Create "OPTION" element
Set its value using setAttribute
Update that to the select element
const topCities = [
{ "id": "1", "name": "Mumbai", "state": "Maharashtra" },
{ "id": "2", "name": "Delhi", "state": "Delhi" },
{ "id": "3", "name": "Bengaluru", "state": "Karnataka" },
{ "id": "4", "name": "Ahmedabad", "state": "Gujarat" },
{ "id": "5", "name": "Hyderabad", "state": "Telangana" },
{ "id": "6", "name": "Chennai", "state": "Tamil Nadu" },
{ "id": "7", "name": "Kolkata", "state": "West Bengal" }
]
const otherCities = [
{ "id": "1", "name": "Bhavnagar", "state": "Bhavnagar" },
{ "id": "2", "name": "Udaipur", "state": "Udaipur" },
{ "id": "3", "name": "Pune", "state": "Pune" },
];
const select = document.querySelector('select');
function addOption(label, value) {
const option = document.createElement("OPTION");
option.setAttribute('value', value);
const text = document.createTextNode(label);
option.appendChild(text);
select.appendChild(option);
}
addOption("---Top Cities---", "1");
topCities.forEach((city) => {
addOption(city.name, city.id);
});
addOption("---Other Cities---", "2");
otherCities.forEach((city) => {
addOption(city.name, city.id);
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<select class="form-select" aria-label="Default select example">
<option selected>Open this select menu</option>
</select>

Related

Sorting API JSON response using Javascript

I am getting below response on hitting DoctorData.api and want to sort them all with their 'ID'. Can someone show me how to sort the Output JSON data and display it same format.
Kindly Excuse my coding skills, this is my second test case. I am new to JS.
var doctorIDgeturl = geturl.geturls.getapiUrl; //'getapiUrl' is Doctor Get API
var res = await api.getRequest(doctorIDgeturl);
logger.logger().info('GET_data = ', JSON.stringify(res.data, null, 2));
var rescount = Object.keys(res.data.data.doctorList); //doctorList is the API response object for above GET API
console.log("This is Sorted Id: ");
const sortedResponse = sort(res.data, r => r.doctorListModels.associateId, ['asc']) //using ascending order to sort
console.log(sortedResponse);
Current output:
{
"message": "Record Found",
"data": {
"DoctorsList": [
{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}
Expected output after sorting:
{
"message": "Record Found",
"data": {
"DoctorsList": [
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
},
{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
}
parseInt(r.doctorListModels.associateId) or +r.doctorListModels.associateId
it seems like it sorts the id as string not number
Sorry I can't comment because of low reputation, but here is solution.
const obj = {
"message": "Record Found",
"data": {
"DoctorsList": [{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}]
}
}
const sortedResponse = obj.data.DoctorsList.sort(function(a, b) { return parseInt(a.id) - parseInt(b.id) });
console.log(sortedResponse)
const obj = {
"message": "Record Found",
"data": {
"DoctorsList": [{
"id": "10",
"name": "William",
"launch_date": "2018-01-24T00:00:00.000-05:00"
},
{
"id": "2",
"name": "Snow",
"launch_date": "2017-08-14T00:00:00.000-05:00"
},
{
"id": "33",
"name": "Thomas",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "3",
"name": "Ismail",
"launch_date": "2018-11-29T00:00:00.000-05:00"
},
{
"id": "5",
"name": "Jackson",
"launch_date": "2018-04-10T00:00:00.000-05:00"
}
]
}}
obj.data.DoctorsList = obj.data.DoctorsList.sort((a, b) => parseInt(a.id) > parseInt(b.id));
console.log(obj)

how to write code to append code and run values from the given json data

getting the result by this code is
https://upxstart.com/api.html
I want to show 'Y'or 'N' in the column Mon, Tue, Wed, Thu, Fri, Sat, Sun
unable to fetch the 'run' value from the json data. I use user.days to get the value of 'run' but it doesn't work. Please tell me the correct code to write there.
json data is:
{
"total": 6,
"response_code": 200,
"trains": [{
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "12:35",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "15097",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
},
{
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}
],
"travel_time": "46:35",
"name": "AMARNATH EXP",
"src_departure_time": "14:00",
"days": [{
"runs": "N",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "N",
"code": "SUN"
}]
},
{
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "12:35",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "15651",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
}, {
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}],
"travel_time": "46:35",
"name": "GHY-JAT LOHIT EXPRESS",
"src_departure_time": "14:00",
"days": [{
"runs": "Y",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "N",
"code": "WED"
}, {
"runs": "N",
"code": "THU"
}, {
"runs": "N",
"code": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "N",
"code": "SUN"
}]
}, {
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "13:40",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "15655",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
}, {
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}],
"travel_time": "47:00",
"name": "KYQ - SVDK EXPRESS",
"src_departure_time": "14:40",
"days": [{
"runs": "N",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "N",
"code": "WED"
}, {
"runs": "N",
"code": "THU"
}, {
"runs": "N",
"code": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "Y",
"code": "SUN"
}]
}, {
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "11:50",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "12491",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
}, {
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}],
"travel_time": "21:50",
"name": "MOURDHWAJ EXPRESS",
"src_departure_time": "14:00",
"days": [{
"runs": "N",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "N",
"code": "WED"
}, {
"runs": "N",
"code": "THU"
}, {
"runs": "N",
"code": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "Y",
"code": "SUN"
}]
}, {
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "12:35",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "12587",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
}, {
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}],
"travel_time": "22:15",
"name": "AMAR NATH EXP",
"src_departure_time": "14:20",
"days": [{
"runs": "Y",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "N",
"code": "WED"
}, {
"runs": "N",
"code": "THU"
}, {
"runs": "N",
"code": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "N",
"code": "SUN"
}]
}, {
"to_station": {
"code": "JAT",
"lat": 32.7058783,
"name": "JAMMU TAWI",
"lng": 74.8798454
},
"dest_arrival_time": "12:35",
"from_station": {
"code": "GKP",
"lat": 29.4438165,
"name": "GORAKHPUR",
"lng": 75.67026469999999
},
"number": "15653",
"classes": [{
"name": "FIRST CLASS",
"code": "FC"
}, {
"name": "THIRD AC",
"code": "3A"
}, {
"name": "3rd AC ECONOMY",
"code": "3E"
}, {
"name": "SLEEPER CLASS",
"code": "SL"
}, {
"name": "FIRST AC",
"code": "1A"
}, {
"name": "SECOND AC",
"code": "2A"
}, {
"name": "SECOND SEATING",
"code": "2S"
}, {
"name": "AC CHAIR CAR",
"code": "CC"
}],
"travel_time": "46:35",
"name": "AMARNATH EXPRESS",
"src_departure_time": "14:00",
"days": [{
"runs": "N",
"code": "MON"
}, {
"runs": "N",
"code": "TUE"
}, {
"runs": "Y",
"code": "WED"
}, {
"runs": "N",
"code": "THU"
}, {
"runs": "N",
"code": "FRI"
}, {
"runs": "N",
"code": "SAT"
}, {
"runs": "N",
"code": "SUN"
}]
}
],
"debit": 1
}
<html>
<head>
<title>train api</title>
</head>
<body>
<h1>Users List</h1>
<table id="users-list">
<thead>
<tr>
<th>From</th>
<th>To</th>
<th>Train Name</th>
<th>train No.</th>
<th>Departure Time</th>
<th>Arival Time</th>
<th>Travel Time</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
<th>Sun</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<!-- load users here -->
</tbody>
</table>
<script>
window.onload = () => {
const SERVER_URL = 'https://api.railwayapi.com/v2/between/source/gkp/dest/jat/date/06-06-2019/apikey/--------/';
// get table element
const table = document.querySelector('#users-list');
// call API using `fetch`
fetch(SERVER_URL)
.then(res => res.json())
.then(res => {
// loop over all users
res.trains.map(user => {
// create a `tr` element
const tr = document.createElement('tr');
// create from station `td`
const frSt = document.createElement('td');
frSt.textContent = user.from_station.name;
// create To station `td`
const toSt = document.createElement('td');
toSt.textContent = user.to_station.name;
// create Train Name `td`
const trNm = document.createElement('td');
trNm.textContent = user.name;
// create train no. `td`
const idTd = document.createElement('td');
idTd.textContent = user.number;
// create Departure time `td`
const deTm = document.createElement('td');
deTm.textContent = user.src_departure_time;
// create Arival time `td`
const arTm = document.createElement('td');
arTm.textContent = user.dest_arrival_time;
// create Travel time `td`
const trTm = document.createElement('td');
trTm.textContent = user.travel_time;
// create Mon `td`
const mon = document.createElement('td');
mon.textContent = user.days;
// create Name `td`
const nameTd = document.createElement('td');
nameTd.textContent = `${user.first_name} ${user.last_name}`;
//create email `td`
const emailTd = document.createElement('td');
emailTd.textContent = user.email;
// add tds to tr
tr.appendChild(frSt);
tr.appendChild(toSt);
tr.appendChild(trNm);
tr.appendChild(idTd);
tr.appendChild(deTm);
tr.appendChild(arTm);
tr.appendChild(trTm);
tr.appendChild(mon);
tr.appendChild(nameTd);
tr.appendChild(emailTd)
// app tr to table
table.querySelector('tbody').appendChild(tr);
});
})
.catch(err => console.log('Error:', err));
};
</script>
</body>
</html>
When it comes to days you should write some thing like this,
user.days.forEach(day => {
let day1 = document.createElement('td');
day1.textContent = day.runs;
});

Error when I try to parse my json

I am using AngularJs doing a simple application And I want to set a variable up in a javascript file in orther to call a json file.
This is my data.js :
[{
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
And this is my data.json
[{
"date":"01/05/2016"
}]
I call my data here.
angular.module("myApp",['zingchart-angularjs'])
.controller('MainController', ['$scope', '$http', function($scope, $http) {
$scope.chartBase = {
"type": "line",
"plotarea": {
"adjust-layout": true /* For automatic margin adjustment. */
},
"scale-x": {
"label": {
"text": "Above is an example of a category scale" /* Add a scale title with a label object. */
},
"labels": ["name1", "name2", "name3"] /* Add your scale labels with a labels array. */
},
"series": [{
"values": [15, 18, 11] //here the prices of city selected
},{
"values": [10, 11, 14] //here the qte of city selected
}]
};
$scope.chartData = angular.copy($scope.chartBase);
$http.get('data.js')
.then(function(response) {
$scope.cities = response.data; // save the request data
$scope.selectedCity = $scope.cities[0]; // select the first one
$scope.changeCity(); // update chart
}, function(error) { console.log(error); });
$scope.changeCity = function() {
if($scope.selectedSubCity || $scope.selectedCity){ // if something has been selected
$scope.data = ($scope.selectedSubCity || $scope.selectedCity).elements; // update elements field
// initialize the array to be displayed in chart
var labels = [];
var price = {
"values": []
};
var qte = {
"values": []
};
// fill the arrays to be displayed from the selected city (sub city)
angular.forEach($scope.data, function(item, index) {
labels.push(item.name);
price.values.push(parseInt(item.price));
qte.values.push(parseInt(item.qte));
});
console.log($scope.chartData)
// put selected values to the field that is used to render the chart
$scope.chartData["scale-x"].labels = labels;
$scope.chartData.series = [ price, qte ];
}
}
}]);
When I run this, the browser tell that I have this error :
SyntaxError: Unexpected token v in JSON at position 5
at Object.parse (native)
You can't have those in your data.js file as they are not valid JSON
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
The error is pointing to the first "v" of "var". You can test your JSON here http://json.parser.online.fr/ on some other online validator.
Your file should look like this:
[{
"name": "city A",
"elements": [{
"id": "c01",
"name": "name1",
"price": "15",
"qte": "10"
}, {
"id": "c02",
"name": "name2",
"price": "18",
"qte": "11"
}, {
"id": "c03",
"name": "name3",
"price": "11",
"qte": "14"
}],
"subsities": [{
"name": "sub A1",
"elements": [{
"id": "sub01",
"name": "nameSub1",
"price": "1",
"qte": "14"
}, {
"id": "sub02",
"name": "nameSub2",
"price": "8",
"qte": "13"
}, {
"id": "sub03",
"name": "nameSub3",
"price": "1",
"qte": "14"
}]
}, {
"name": "sub A2",
"elements": [{
"id": "ssub01",
"name": "nameSsub1",
"price": "1",
"qte": "7"
}, {
"id": "ssub02",
"name": "nameSsub2",
"price": "8",
"qte": "1"
}, {
"id": "ssub03",
"name": "nameSsub3",
"price": "4",
"qte": "19"
}]
}, {
"name": "sub A3",
"elements": [{
"id": "sssub01",
"name": "nameSssub1",
"price": "1",
"qte": "11"
}, {
"id": "sssub02",
"name": "nameSssub2",
"price": "2",
"qte": "15"
}, {
"id": "sssub03",
"name": "nameSssub3",
"price": "1",
"qte": "15"
}]
}]
}, {
"name": "city B",
"elements": [{
"id": "cc01",
"name": "name11",
"price": "10",
"qte": "11"
}, {
"id": "cc02",
"name": "name22",
"price": "14",
"qte": "19"
}, {
"id": "cc03",
"name": "name33",
"price": "11",
"qte": "18"
}]
}, {
"name": "city C",
"elements": [{
"id": "ccc01",
"name": "name111",
"price": "19",
"qte": "12"
}, {
"id": "ccc02",
"name": "name222",
"price": "18",
"qte": "17"
}, {
"id": "ccc03",
"name": "name333",
"price": "10",
"qte": "5"
}]
}]
var data = require('data_old.json');
var json = JSON.parse(data);
alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016
Why do you add those at the beginning of the JSON ? They cannot be parsed by your script, thus displaying the Syntax Error. What do you want to do exactly ?

Populating select options using jquery fails

I was trying to populate select options from a JSON using jquery. Here is my html form code (with search options) -
<div class="form-group row">
<label for="" class="col-sm-2 form-control-label">Country</label>
<div class="col-sm-10">
<select class="form-control selectpicker" id="country" placeholder="" data-live-search="true">
</select>
</div>
</div>
And here is the code i have write to populate the form with documents and also catch and echo the selection -
(function() {
var url = "dummy.json";
countries = [];
divisions = [];
districts = [];
subdistricts = [];
$.getJSON(url)
.done(function( data ) {
countries.push(data['Country']);
divisions.push(data['Divisions']);
districts.push(data['Districts']);
subdistricts.push(data['Subdistricts']);
$('#country').empty();
for(i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens="' + countries[0][i]["name"] +'" value="' + i + '">' + countries[0][i]["name"] + '</option>');
};
$('#country').change(function(){
var selected = $( this ).val();
console.log(selected);
});
});
})();
My problem is- the selection form is not populating after running the code. Is there any syntax error in my code ? Or am i approaching it in wrong way ? If anyone want to see the json file, i will post it here.
Here is my JSON file -
{
"Country": [
{
"id": "01",
"name": "China",
"capital": "Beijing",
"divisions": "[01, 02, 03]",
"districts": "[01, 02, 03]"
},
{
"id": "02",
"name": "Bangladesh",
"capital": "Dhaka",
"divisions": "[04,05,06,07,08,09,10,11]",
"Districts": "[04,05,06,07,08,09,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]"
},
{
"id": "03",
"name": "Singapore",
"Capital": "Singapore City",
"Divisions": "[12,13,14,15,16]",
"Districts": "[32,33,34,35,36]"
}
],
"Divisions": [
{
"id": "01",
"name": "Shengdong",
"districts": [
[
"[01]"
]
]
},
{
"id": "02",
"name": "Anhui",
"districts": [
[
"[02]"
]
]
},
{
"id": "03",
"name": "Fujian",
"districts": [
[
"[03]"
]
]
},
{
"id": "04",
"name": "Barisal",
"districts": "[4,5,6]"
},
{
"id": "05",
"name": "Chittagong",
"Districts": "[07,08,09,10]"
},
{
"id": "06",
"name": "Dhaka",
"Districts": "[11,12]"
},
{
"id": "07",
"name": "Khulna",
"Districts": "[13,14]"
},
{
"id": "08",
"name": "Central Region",
"Districts": [
[
"[15]"
]
]
},
{
"id": "09",
"name": "North Region",
"Districts": [
[
"[16]"
]
]
},
{
"id": "10",
"name": "East Region",
"Districts": [
[
"[17]"
]
]
},
{
"id": "11",
"name": "North-east Region",
"Districts": [
[
"[18]"
]
]
},
{
"id": "12",
"name": "West Region",
"Districts": [
[
"[19]"
]
]
}
],
"Districts": [
{
"id": "1",
"name": "Dongcheng",
"Subdistricts": [
[
"[1]"
]
]
},
{
"id": "2",
"name": "Yaohai",
"Subdistricts": [
[
"[2]"
]
]
},
{
"id": "3",
"name": "Luyang",
"Subdistricts": [
[
"[3]"
]
]
},
{
"id": "4",
"name": "Barisal",
"Subdistricts": [
[
"[4]"
]
]
},
{
"id": "5",
"name": "Barguna",
"Subdistricts": [
[
"[5]"
]
]
},
{
"id": "6",
"name": "Bhola",
"Subdistricts": "[6,7]"
},
{
"id": "7",
"name": "Chittagong",
"Subdistricts": "[8,9,10,11]"
},
{
"id": "8",
"name": "Cox's Bazar",
"Subdistricts": [
[
"[12]"
]
]
},
{
"id": "9",
"name": "Comilla",
"Subdistricts": [
[
"[13]"
]
]
},
{
"id": "10",
"name": "Feni",
"Subdistricts": [
[
"[14]"
]
]
},
{
"id": "11",
"name": "Dhaka",
"Subdistricts": [
[
"[15]"
]
]
},
{
"id": "12",
"name": "Narayanganj",
"Subdistricts": [
[
"[16]"
]
]
},
{
"id": "13",
"name": "Khulna",
"Subdistricts": [
[
"[17]"
]
]
},
{
"id": "14",
"name": "Bagerhat",
"Subdistricts": [
[
"[18]"
]
]
},
{
"id": "15",
"name": "Radin Mas SMC",
"Subdistricts": [
[
"[19]"
]
]
},
{
"id": "16",
"name": "Jalan Besar GRC",
"Subdistricts": [
[
"[20]"
]
]
},
{
"id": "17",
"name": "Mount Batten GRC",
"Subdistricts": [
[
"[21]"
]
]
},
{
"id": "18",
"name": "Marine Parade GRC",
"Subdistricts": [
[
"[22]"
]
]
},
{
"id": "19",
"name": "West Coast GRC",
"Subdistricts": [
[
"[23]"
]
]
}
],
"Subdistricts": [
{
"id": "1",
"name": "Dailang",
"postcodes": "[736200,404000,100000]"
},
{
"id": "2",
"name": "Changchung",
"postcodes": "[864000,504100,905050]"
},
{
"id": "3",
"name": "Chengdu",
"postcodes": "[994000,909100,109050]"
},
{
"id": "4",
"name": "Agailjhara",
"postcodes": "[8240,8241,8242]"
},
{
"id": "5",
"name": "Amtali Upazella",
"postcodes": "[9940,9941,8878]"
},
{
"id": "6",
"name": "Bhola Sadar",
"postcodes": "[7230,7741,7752]"
},
{
"id": "7",
"name": "Daulatkhan",
"postcodes": "[8650,8871,8880]"
},
{
"id": "8",
"name": "Sitakund",
"postcodes": "[4320,4321,4325]"
},
{
"id": "9",
"name": "Satkania",
"postcodes": "[4460,4461,4458]"
},
{
"id": "10",
"name": "Port",
"postcodes": "[4530,4555,4532]"
},
{
"id": "11",
"name": "Dabal Muring",
"postcodes": "[4320,4321,4448]"
},
{
"id": "12",
"name": "Chokaria",
"postcodes": "[5320,5321,5432]"
},
{
"id": "13",
"name": "Daudkandi",
"postcodes": "[6432,6433,6555]"
},
{
"id": "14",
"name": "Feni sadar",
"postcodes": "[3240,3241,3378]"
},
{
"id": "15",
"name": "Dhanmondi",
"postcodes": "[2330,2441,2878]"
},
{
"id": "16",
"name": "Narayanganj Sadar",
"postcodes": "[6444,6543,6657]"
},
{
"id": "17",
"name": "Batiaghat",
"postcodes": "[7780,7781,7778]"
},
{
"id": "18",
"name": "Bagerhat Sadar",
"postcodes": "[7450,7451,7458]"
},
{
"id": "19",
"name": "Changi",
"postcodes": "[736200,404000,555776]"
},
{
"id": "20",
"name": "Quenstown",
"postcodes": "[787899,878788,987789]"
},
{
"id": "21",
"name": "Clementi",
"postcodes": "[989778,976543,975432]"
},
{
"id": "22",
"name": "Tuas",
"postcodes": "[109901,110900,121345]"
},
{
"id": "23",
"name": "East Region",
"postcodes": "[609098,567654,765432]"
}
]
}
Latest EDIT:
I have checked in the console. HTML form with options value is loading perfectly, but for some reason my form is not showing options. Here is my latest code -
for(var i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens="' + countries[0][i]["name"].toLowerCase() +'" value="' + countries[0][i]["id"] + '">' + countries[0][i]["name"] + '</option>');
};
HTML code after loading in the console -
<select id="country" class="form-control selectpicker" data-live-search="true" placeholder="" tabindex="-98">
<option value="01" data-tokens="china">China</option>
<option value="02" data-tokens="bangladesh">Bangladesh</option>
<option value="03" data-tokens="singapore">Singapore</option>
</select>
Any reason for such phenomenon ?
Change the loop for :
for(var i=0; i<countries[0].length; i++){
$('#country').append('<option data-tokens=' + countries[0][i].name +'value=' + i + '>' + countries[0][i].name + '</option>');
};
Well, it seems my problem was occurring for the selectpicker class i have used. The plugin i have used to generate the search options for the selection has its own criteria for populating options in a select form. Here is the link of their documentation - https://silviomoreto.github.io/bootstrap-select/methods/#selectpickerrefresh
Here is my revised JS code -
(function() {
var url = "dummy.json",
countries = [],
divisions = [],
districts = [],
subdistricts = [],
$.getJSON(url)
.done(function( data ) {
countries.push(data['Country']);
divisions.push(data['Divisions']);
districts.push(data['Districts']);
subdistricts.push(data['Subdistricts']);
var option_string = '';
for(var i=0; i<countries[0].length; i++){
option_string += '<option data-tokens="' + countries[0][i]["name"].toLowerCase() +'" value="' + countries[0][i]["id"] + '">' + countries[0][i]["name"] + '</option>';
}
$('#country').empty().append(option_string).change(function(){
var selected = $(this).val();
console.log(selected);
}).selectpicker('refresh');
});
})();

angular js : set option value after filling options in select

I have a web service which has result like:
{
"selectedStateId": "1",
"selectedCityId": "1",
"selectedAreaId": "1",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
}
Now, I want to bind arrays of states, cities and areas to three different select and set its value using stateId, cityId and areaId that are member of parent object.
Two questions:
how to set values of three different selects ?
How can we achieve (1) if we have array of the objects, the one I have created above ?
Thanks.
Edit: I guess the first two answers got some misunderstanding.. So, changed my data representation. I want to set selectedStateId to be set into select element of states, selectedCityId to be set into select element of cities, and so on.. Now, I guess you should be clear what I am asking for..
Here I have created a plunker for you. Please have a look at it with html having 3 selects
<select>....</select>
"http://plnkr.co/edit/LaypSCATZyQxLHYHjgnB?p=preview"
Alright if you want to create three select from above array each for area , city and states then do following :
Your above response goes like this :
$scope.items = response;
//set default . I am setting first state as default
$scope.selectedstate = response.states[0];
Let's say for states it would be
<select
ng-options="state.stateName as state.label for state in items.states track by state.stateId"
ng-model="selectedstate">
Follow same process for area and city.
For your reference https://docs.angularjs.org/api/ng/directive/ngOptions . Angular way of doing this.
Yet another way with ng-options instead ng-repeat
angular.module('app',[]).controller('ctrl',function($scope){
$scope.data = {
"selectedStateId": "1",
"selectedCityId": "1",
"selectedAreaId": "1",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<select ng-model="data.selectedStateId" ng-options="s.stateId as s.stateName for s in data.states" ></select>
<select ng-model="data.selectedCityId" ng-options="c.cityId as c.cityName for c in data.cities" ></select>
<select ng-model="data.selectedAreaId" ng-options="a.areaId as a.areaName for a in data.areas" ></select>
</div>
Okay I am trying to answer my own question. for those who expect detailed explanation:
Answer for question 1:
To set selected value for select element, we just need to set ng-selectedproperty to optionas below:
Suppose my response is:
$scope.x = {
"selectedStateId": "1",
"selectedCityId": "1",
"selectedAreaId": "1",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
};
Then, in html, we can write like:
<select>
<option ng-selected="{{state.stateId == x.selectedStateId}}" ng-repeat="state in x.states" value="{{state.stateId}}">{{state.stateName}}</option>
</select>
<select>
<option ng-selected="{{city.cityId == x.selectedCityId}}" ng-repeat="city in x.cities" value="{{city.cityId}}">{{city.cityName}}</option>
</select>
<select>
<option ng-selected="{{area.areaId == x.selectedAreaId}}" ng-repeat="area in x.areas" value="{{area.areaId}}">{{area.areaName}}</option>
</select>
Answer for question 2:
Suppose, we have array of this object, say,
$scope.list = [{
"stateId": "1",
"cityId": "1",
"areaId": "1",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
},
{
"stateId": "2",
"cityId": "2",
"areaId": "2",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
},
{
"stateId": "1",
"cityId": "2",
"areaId": "3",
"states": [{
"stateId": "1",
"stateName": "Gujarat"
}, {
"stateId": "2",
"stateName": "Rajasthan"
}],
"cities": [{
"cityId": "1",
"stateId": "1",
"cityName": "Ahmedabad"
}, {
"cityId": "2",
"stateId": "1",
"cityName": "Surat"
}],
"areas": [{
"areaId": "1",
"cityId": "1",
"areaName": "thaltej"
}, {
"areaId": "2",
"cityId": "1",
"areaName": "Maninagar"
}, {
"areaId": "3",
"cityId": "1",
"areaName": "Naranpura"
}]
}];
In this case, we need a wrapper to wrap all the selects so that we can iterate list over it.
So, I took a simple <div>..</div> that will do in my case, as below:
<div ng-repeat="x in list">
<select>
<option ng-selected="{{state.stateId == x.stateId}}" ng-repeat="state in x.states" value="{{state.stateId}}">{{state.stateName}}</option></select>
<select>
<option ng-selected="{{city.cityId == x.cityId}}" ng-repeat="city in x.cities" value="{{city.cityId}}">{{city.cityName}}</option></select>
<select>
<option ng-selected="{{area.areaId == x.areaId}}" ng-repeat="area in x.areas" value="{{area.areaId}}">{{area.areaName}}</option></select>
</div>

Categories

Resources