select dropdown shows last value first - javascript

I have two four dropdowns, second dropdown selected and if I select first dropdown, second dropdown populates the value but shows last element first instead of first
sample data get the dropdown values
var countrydata ={
countries:[{
"country_code": "TH",
"country_name": "Thailand",
"currency_from": [
"THB",
"USD"
],
"currency_to": [
"THB"
],
"popular_to": [
"Malaysia",
"Myanmar"
],
"name": {
"en": "Thailand",
"th": "ประเทศไทย"
},
"normalized_name": {
"en": "thailand"
}
},
{
"country_code": "SG",
"country_name": "Singapore",
"currency_from": [
"SGD",
"USD"
],
"currency_to": [
"SGD"
],
"popular_to": [
"India",
"United States"
],
"name": {
"en": "Singapore",
"fr": "Singapour",
"zh": "新加坡"
},
"normalized_name": {
"en": "singapore"
}
}]
}
var currencydata = {
currencies:[{
"currency": "SGD",
"country_code": "SG",
"country_name": "Singapore",
"name": {
"en": "Singapore Dollar",
"fr": "Dollar Singapour",
"zh": "新加坡元"
},
"default_amount": "1000"
},
{
"currency": "THB",
"country_code": "TH",
"country_name": "Thailand",
"name": {
"en": "Thailand Baht",
"th": "เงินบาทไทย"
},
"default_amount": "9000"
},
}]}
index.js file sample
updateSendCountry(value) {
this.sendvalue = this.countrydata.countries.filter(function (item) {
return item.country_code == value;
})
if (this.sendvalue && this.sendvalue[0].currency_to) {
var sendcurrency = this.sendvalue[0].currency_to[0];
this.updateSendCurrency(sendcurrency);
}
}
updateSendCurrency(e) {
this.ccyvalue = this.currencydata.currencies.filter(function (item) {
return item.currency == e;
})
}
<select name="send_country" class="form-control" id="send_country" #change="${this.sendcountryChange}">
${this.countrydata.countries.map((country, key) => html`<option value=${country.country_code}>${country.country_name}</option>`)}
</select>
</div>
<div class="input-group p-2">
<div class="input-group-prepend">
<select name="sccy" class="form-control" id="sccy" #change="${this.updateSendCurrency}">
${this.sendvalue.map((currency) => currency.currency_from.map((send) =>
html`<option value=${send}>${send}</option>`))
}
</select>
eg:
Dropdown A -> Singapore populates Dropdown B -> SGD, USD
Dropdown A -> Thailand populates Dropdown B -> THB, USD
if dropdown A selection shows Singapore, SGD USD in Dropdown B
if USD selected in Dropdown B then i change Dropdown A to thailand it Dropdow B
populates THB, USB but shows USD first(second option) rather than THB

this.sendvalue.map(...) is going to update the state (attributes and content) of the <option> elements, but it won't necessarily replace them. This means that when you change the list, the first option will have its text changed from SGD to THB, but the second option (USD) will still be selected.
If you want to control the selection state, you'll need to store it and use something like this for your item template:
this.sendvalue.map((currency, index) => currency.currency_from.map((send) =>
html`<option value=${send} ?selected=${index === selectedIndex}>${send}</option>`))
Here I'm using a variable selectedIndex to store the selected index. You'd have to reset it when changing the country.

Related

how can I reach to cities of the the specific country that user choose

if I have an input and the user have to choose a country from a list, and I have an array of object
[
{
"id":1,
"country": "Afghanistan",
"cities": [
"Herat",
"Kabul",
"Kandahar",
"Molah"
]
},
{
"id":2,
"country": "Albania",
"cities": [
"Elbasan",
"Petran",
"Pogradec"
]
},
{
"id":3,
"country": "Algeria",
"cities": [
"Algiers",
"Annaba",
"Azazga",
"Batna City"
]
}]
how can I reach to cities of the the specific country that user choose?
If you have tags in HTML with values of "id"s in this JSON data. Then whenever the user clicks on each of the countries, you will have the id of that country in your JS with something like this:
var country_id = document.getElementById("IdOfSelectTag").value
Then, you can just filter the cities that are part of that ID by using (if you named the JSON data as "countries_data"):
countries_data.find(e => e.coutry === country_id)
You can then put "countries_data" into a table, select, etc. tags in HTML to show it to users.

Country->State->City Dependent dropdown showing 'object [Object]

I'm building a dependent dropdown for country, state and city. It's not going very well. I've done extensive research on the subject on Stackoverflow and other sites on the web for the past few days and have not been able to get the '#state' select object to populate states based on the selected '#country' select object which is populating countries from json just fine. The states are not populating after the country is selected based on the 'change' method. I have an 'if' statement which says, 'if the selected #country === 'US' (which displays as North America), then load the US states and territories .json file.
After fiddling around with the code, I have finally been able to get the '#state' dropdown to at least display 'object [Object]', so I know I'm getting closer to a solution. I'm not quite sure why it's displaying 'object[Object]' in the state dropdown. It may be a 'type' error of some sort where json is being displayed as an object instead of a string as it should but I don't understand how to fix this in the context of my code.
Any help would be greatly appreciated.
Here is the HTML:
<!doctype html>
<html>
<head>
<title>Country->State->City</title>
</head>
<body>
Country:
<select id="country">
<pre><option selected value="base">Select Country</option><pre>
</select>
State:
<select id="state">
<option selected value="base">Select state</option>
</select>
City:
<select id="city">
<option selected value="base">Select City</option>
</select>
<script type = "text/javascript" src="jquery-2.2.4.min.js"></script>
<script type = "text/javascript" src="custom.js"></script>
</body>
</html>
jQuery
$(function(){
let countryOptions;
let stateOptions;
let gaCitiesOps;
$.getJSON('countries.json',function(data){
$.each(data, function(i,country) {
countryOptions+=
'<option value= "'+country.code+'">'
+country.name+
'</option>';
});
$('#country').html(countryOptions);
});
$("#country").change(function(){
if($(this).val()==="US"){
$.getJSON('us_states.json',function(data){
$.each(data, function(stateCode,stateName) {
stateOptions+='<option value="'+stateCode+'">'
+stateName+
'</option>';
});
$('#state').html(stateOptions);
});
}
});
$("#state").change(function(){
if($(this).val()==="GA"){
$.getJSON('GA_cities.json',function(data){
$.each(data, function(statecode,city) {
gaCitiesOps +='<option value="'+statecode+'">'
+city+
'</option>';
});
$('#city').html(gaCitiesOps);
});
}
});
});
Countries.json
[
{
"code": "US",
"name": "North America"
},
{
"code": "AG",
"name": "Antigua"
},
{
"code": "AU",
"name": "Australia"
},
{
"code": "AT",
"name": "Austria"
},
{
"code": "BG" ,
"name": "Bulgaria"
},
{
"code": "CA",
"name": "Canada"
},
.....ect
us_states.json
[
{
"stateCode": "AL",
"name": "Alabama"
},
{
"stateCode": "AR",
"name": "Arkansas"
},
{
"stateCode": "AS",
"name": "American Samoa"
},
{
"stateCode": "AZ",
"name": "Arizona"
},
{
"stateCode": "CA",
"name": "California"
},
.....etc
GA_cities.json
[
{
"code": "ALB",
"name": "ALBANY"
},
{
"code": "AMR",
"name": "AMERICUS"
},
{
"code": "ATH",
"name": "ATHENS"
},
{
"code": "ATL",
"name": "ATLANTA"
},
{
"code": "AUG",
"name": "AUGUSTA"
},
{
"code": "BAI",
"name": "BAINBRIDGE"
},
....etc
Thanks for your consideration!
You're using $.each incorrectly. First argument is the index/key, second is the value. In your case you iterate over array of objects - so first argument is an index and second is each contained object. Use this code for states:
$.each(data, function(index,stateObj) {
stateOptions+='<option value="'+stateObj.stateCode+'">'
+stateObj.name+
'</option>';
});
$('#state').html(stateOptions);
});
And this for cities:
$("#state").change(function(){
if($(this).val()==="GA"){
$.getJSON('GA_cities.json',function(data){
$.each(data, function(index,city) {
gaCitiesOps +='<option value="'+city.code+'">'
+city.name+
'</option>';
});
$('#city').html(gaCitiesOps);
});
}
});
You can also add options using JS APIs which is slightly better than constructing the entire options HTML as a string and dumping it into html(). See this question for the alternative methods.
console.log() is your best friend. Try logging the values you get from $.each and you will know why you're getting [object Object].
$.each(data, function(stateCode, stateName));
Output is stateCode 0, stateName {stateCode: "AL", name: "Alabama"}
$.each arguments are (key, value) and you are looping over an array so key (stateCode in this case) is index of the array.
ES6; If you wanna be fancy you can destructure the arguments to
$.each(key, {stateCode, name});

Filter JSON based on selected dropdown option

I have a JSON file with a list of countries which has 2 keys: "name" and "areacode". I have dropdown with a list of options that has a value attr witch is the same as the "name" key in the JSON file.
Long story short: I want to display the "areacode" value in the json file when the selected option in the dropdown matches the "name" value in the JSON file
UPDATE
I have pasted the code here: http://codepen.io/sarfehjou/pen/RpKMWE
The only difference is that in my solution I have to get the JSON file by a url
HTML
<select>
<option value="Afghanistan GLOBAL">Afghanistan GLOBAL</option>
<option value="Albenter code hereania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
</select>
Script
var list = {
"countries": [
{
"name": "Afghanistan GLOBAL",
"areacode": ""
},
{
"name": "Albania",
"areacode": ""
},
{
"name": "Algeria",
"areacode": ""
},
{
"name": "American Samoa",
"areacode": ""
},
{
"name": "Andorra",
"areacode": ""
}
]
}
Your question is quite vague as already established, i.e. not sure what you need to do with area code and stuff? anyway this is what i could work out:
basically added an event listener on the select and whenever you change it, looks up the value from list (the list can be from the server or cached).
Have a look, if you get more ideas asks some more.
var list = {
"countries": [
{
"name": "Afghanistan GLOBAL",
"areacode": "8787"
},
{
"name": "Albania",
"areacode": "446"
},
{
"name": "Algeria",
"areacode": "212"
},
{
"name": "American Samoa",
"areacode": "767"
},
{
"name": "Andorra",
"areacode": "5454"
}
]
}
var countrySelect = document.getElementById('countrySelect');
countrySelect.addEventListener('change', function(e) {
console.log(this.value);
console.log(findAreaCode(this.value));
});
function findAreaCode(name) {
var resultItems = list.countries.filter(function(currentItem) {
return currentItem.name == name;
})
console.log(resultItems[0]);
return resultItems[0]? resultItems[0].areacode: 'N/A';
}
<select id="countrySelect">
<option value="Afghanistan GLOBAL">Afghanistan GLOBAL</option>
<option value="Albenter code hereania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
</select>
I have pasted the code her: http://codepen.io/sarfehjou/pen/RpKMWE
The only different is that in my solution I have to get the json file by a url
<select>
<option value="Afghanistan GLOBAL">Afghanistan GLOBAL</option>
<option value="Albenter code hereania">Albania</option>
<option value="Algeria">Algeria</option>
<option value="American Samoa">American Samoa</option>
<option value="Andorra">Andorra</option>
</select>
var list = {
"countries": [
{
"name": "Afghanistan GLOBAL",
"areacode": ""
},
{
"name": "Albania",
"areacode": ""
},
{
"name": "Algeria",
"areacode": ""
},
{
"name": "American Samoa",
"areacode": ""
},
{
"name": "Andorra",
"areacode": ""
}
]
}
To answer your question, you can do this,
$.getJSON("http://api/somejsonfile/",function(data){
// Initializing an empty array
var options=[];
// Running a loop on the response JSON and adding the options to a string array
$.each(data.countries,function(id,eachcountry){
options.push("<option value='"+eachcountry.areacode+"'>"+eachcountry.name+"</option>");
});
// Joining the string and replacing it inside the select element
$(".dropdown").html(options.join(""));
});
This is a rough implementation so there might be some syntactical issues!!
Adding a simple example
$(document).ready(function(){
// This is a sample country code JSON from Github
$.getJSON("https://gist.githubusercontent.com/Goles/3196253/raw/9ca4e7e62ea5ad935bb3580dc0a07d9df033b451/CountryCodes.json",function(data){
// Initializing an empty array
var options=[];
// Running a loop on the response JSON and adding the options to a string array
$.each(data,function(id,eachcountry){
options.push("<option value='"+eachcountry.dial_code+"'>"+eachcountry.name+"</option>");
});
// Joining the string and replacing it inside the select element
$(".dropdown").html(options.join(""));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdown">
<option value="">Select</option>
</select>

Angular Drop down with dependencies on first drop down

I have two drop down fields where the second one is dependent on the selection in the first.
The data for the first drop down comes from one data set. It lists the number associated with an account ng-repeat="option in acctList": 1, 4 and 7.
I want to go to a different data set, find the account numbers that match, and then show the Customers that are related to that account. (account 1 has customers 1-2, account 4 has customers 3-4, and account 7 has customers 5-7). The second drop down should show nothing (blank) when nothing has been selected in the first.
Here is my plunker with the two drop downs: http://plnkr.co/edit/jDitkge1rx6GJzkdElJO?p=preview
Here is my controller:
angular.module("app", [])
.controller("MainCtrl", function($scope) {
$scope.test = "This is a test";
$scope.defnum = 1;
$scope.acct_info = [
{
"Req": "MUST",
"DefCom": "1"
},
{
"Req": "NoMUST",
"DefCom": "5"
},
{
"Req": "MUST",
"DefCom": "4"
},
{
"Req": "MUST",
"DefCom": "7"
}
];
$scope.cust_info = [
{
"Customer": "1",
"Com": "1"
},
{
"Customer": "2",
"Com": "1"
},
{
"Customer": "3",
"Com": "4"
},
{
"Customer": "4",
"DefCom": "4"
},
{
"Customer": "5",
"DefCom": "7"
},
{
"Customer": "6",
"DefCom": "7"
},
{
"Customer": "7",
"DefCom": "7"
}
];
});
I added ng-repeat="option in cust_info | filter:{ Com : filter.DefCom }" to try to filter the second based on this SO answer: Filter ng-options from ng-options selection
But it's not working.
I've tried using ng-change, but I think there should be an easier way, like a filter or track by. I'm wondering also if I should change from ng-repeat to ng-option. Anyone have insight on an easy way to do this?
Use ng-if in your second <option> tag, may it is, whatever you want
<select>
<option ng-selected="defnum == option.DefCom" ng-repeat="option in acct_info | filter:{Req:'MUST'}:true">
{{ option.DefCom }}
</option>
</select>
<select>
<option ng-if="option.DefCom" ng-selected="" ng-repeat="option in cust_info">
{{ option.Customer}}
</option>
</select>

Query JSON node value with another node's value

New to JSON so I'll do my best here. I have a JSON object called HUDS. Below are 2 sample nodes (by the way, can I call these nodes in JSON like in XML?).
var HUDS = [
{
"DISTRICT": "100",
"BIOS": "BROWN",
"AREA_KM": "3663.158164",
"AREA_MI": "1414.347616",
"NAME": "100",
"REG": "1",
"ACRES": "905182",
"EMU_Name": "Purcell",
"Shape_Leng": "299746.4938",
"Shape_Area": "3663158164",
},
{
"DISTRICT": "101",
"BIOS": "THIER",
"AREA_KM": "1507.774765",
"AREA_MI": "582.152762",
"NAME": "101",
"REG": "1",
"ACRES": "372578",
"EMU_Name": "Salish",
"Shape_Leng": "229150.0655",
"Shape_Area": "1507774766",
}
]
I have a drop down form that will be used to specify a value specific to the "BIOS" field in my JSON. For example the user could select BROWN from the dropdown menu.
I'd then like to create a var that can be used to fill in a div. For example when the user selects BROWN I'd like my div to fill with the value from "EMU_Name"
I know this is wrong but maybe it conveys what I am going for
function dropDownAction(){
var tempBios=document.BIOSForm.BIOS.value;
var tempEmuValue=HUDS.BIOS==tempBios.EMU_Name;
document.getElementById("mydiv").innerHTML=tempEmuValue;
}
Try:
<form name="BIOSForm">
<select name="BIOS" onchange="dropdownaction();">
<option value="BROWN">BROWN</option>
<option value="THEIR">THEIR</option>
</select>
</form>
<div id="emuname">
</div>
<script type='text/javascript'>
var HUDS = [
{
"DISTRICT": "100",
"BIOS": "BROWN",
"AREA_KM": "3663.158164",
"AREA_MI": "1414.347616",
"NAME": "100",
"REG": "1",
"ACRES": "905182",
"EMU_Name": "Purcell",
"Shape_Leng": "299746.4938",
"Shape_Area": "3663158164",
},
{
"DISTRICT": "101",
"BIOS": "THIER",
"AREA_KM": "1507.774765",
"AREA_MI": "582.152762",
"NAME": "101",
"REG": "1",
"ACRES": "372578",
"EMU_Name": "Salish",
"Shape_Leng": "229150.0655",
"Shape_Area": "1507774766",
}
]
function dropdownaction(){
for(var x=0;x<HUDS.length;x++){
var tempBios = document.BIOSForm.BIOS.value;
if(tempBios == HUDS[x].BIOS){
document.getElementById("emuname").innerHTML = HUDS[x].EMU_Name;
break;
}
}
}
</script>

Categories

Resources