I have created an address selection boxes. If you select a region it will display the provinces included in that region. If I select the province, it will display in the list the municipalities in that province. Lastly, if I select the municipality, it will show the towns included in that municipality. This is working fine for the first 5 regions. But for the rest, it works only for the region and province. This is the live demo --> https://ar-ey.github.io/phplaces/
Here is my html code:
<body>
<select name="regions" id="regions">
<option value="" disabled selected>Select</option>
</select><br>
<select name="provinces" id="provinces">
<option value="" disabled selected>Select</option>
</select><br>
<select name="" id="municipalities">
<option value="" disabled selected>Select</option>
</select><br>
<select name="" id="barangays">
<option value="" disabled selected>Select</option>
</select><br>
<script src="./app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is the javascript code:
// get first dropdown and bind change event handler
$('#regions').change(function() {
// get optios of second dropdown and cache it
var $options = $('#provinces')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
$('#provinces').change(function() {
// get optios of second dropdown and cache it
var $options = $('#municipalities')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
})
$('#municipalities').change(function() {
// get optios of second dropdown and cache it
var $options = $('#barangays')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
})
})
let regions = [];
let provinces = [];
let municipalities = [];
let barangays = [];
function showRegions(){
const dropdown = document.getElementById('regions')
for (var i = 0; i < regions.length; i++) {
var option = document.createElement("option");
option.value = regions[i].regCode;
option.text = regions[i].regDesc;
dropdown.appendChild(option);
}
}
function showProvinces(){
const dropdown = document.getElementById('provinces')
for (var i = 0; i < provinces.length; i++) {
var option = document.createElement("option");
option.value = provinces[i].provCode;
option.text = provinces[i].provDesc;
option.setAttribute('data-val',provinces[i].regCode);
dropdown.appendChild(option);
}
}
function showMunicipalities(){
const dropdown = document.getElementById('municipalities')
for (var i = 0; i < municipalities.length; i++) {
var option = document.createElement("option");
option.value = municipalities[i].citymunCode;
option.text = municipalities[i].citymunDesc;
option.setAttribute('data-val',municipalities[i].provCode)
dropdown.appendChild(option);
}
}
function showBarangays(){
const dropdown = document.getElementById('barangays')
for (var i = 0; i < barangays.length; i++) {
var option = document.createElement("option");
option.value = barangays[i].brgyCode;
option.text = barangays[i].brgyDesc;
option.setAttribute('data-val',barangays[i].citymunCode)
dropdown.appendChild(option);
}
}
fetch("./json/refregion.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
regions = data.RECORDS;
showRegions()
})
fetch("./json/refprovince.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
provinces = data.RECORDS;
showProvinces()
})
fetch("./json/refcitymun.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
municipalities = data.RECORDS;
showMunicipalities()
})
fetch("./json/refbrgy.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
barangays = data.RECORDS;
showBarangays()
})
Related
I have two drop down lists, second is dependent on the first one. What I don´t know is how add different value to node.value (value of option element).
EDIT: At this moment I have same value in textContent and in value of html option element but I need to add different value from textContent.
e.g. Inhabitants
var moduly = [];
moduly['1'] = ["Inhabitants", "Married"];
moduly['2'] = ["German", "French", "English"];
moduly['3'] = ["Houses", "Estates"];
moduly['4'] = ["Surface area", "Meadow area"];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose module";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element;
node.textContent = element;
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
</form>
You are using a var that isn't defined, which throws an error:
var elementvalue = mvalue[this.value.toString().toLowerCase()];
Because the var elementvalue is also not used, you can comment that line out or delete it. Furthermore you try to clone a select element with the name itemSelect which doesn't exist in this example code. The following line is missing:
<select id="itemSelect" name="itemSelect"></select>
Fix both errors and yout code should work as expected.
Working example: (i added a disabled option like in the second select so that you can select the first option "Demographics" and renamed the second disabled option from "Choose modul" to "Choose item" so that you can differentiate between both)
var moduly = [];
moduly['1'] = ["Inhabitants", "Married"];
moduly['2'] = ["German", "French", "English"];
moduly['3'] = ["Houses", "Estates"];
moduly['4'] = ["Surface area", "Meadow area"];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
//var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose item";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element;
node.textContent = element;
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="0" disabled selected>Choose module</option>
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
<select id="itemSelect" name="itemSelect"></select>
</form>
If you want different value/content pairs you can nest your moduly array one step deeper. Change the array for example from:
moduly['3'] = ["Houses", "Estates"];
to
moduly['3'] = [["10", "Houses"], ["11", "Estates"]];
Then you just need to output the data with array notation:
node.value = element[0];
node.textContent = element[1];
var moduly = [];
moduly['1'] = [["5", "Inhabitants"], ["6", "Married"]];
moduly['2'] = [["7", "German"], ["8", "French"], ["9", "English"]];
moduly['3'] = [["10", "Houses"], ["11", "Estates"]];
moduly['4'] = [["12", "Surface area"], ["13", "Meadow area"]];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
//var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose item";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element[0];
node.textContent = element[1];
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="0" disabled selected>Choose module</option>
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
<select id="itemSelect" name="itemSelect"></select>
</form>
I have 2 select's. I want to move items between them. They should be sorted. I grabbed some code from SO, and am experiencing something weird. When I pass the element as a parameter to the sort function, it doesn't work. When I explicitly get the element in the sort function it works perfectly. Look at the first line in the sort function and you'll see what I'm talking about.
Here's my PHP part.
echo "
<div><select id='listBox1' class='form-control select-manage-category' size='5'>
<option value=1>1-text</option>
<option value=2>2-text</option>
<option value=3>3-text</option>
<option value=4>4-text</option>
</select></div>
<input id='add-category' onclick='ClickAdd()' name='add' type='button' value='Add Item'>
<input id='remove-category' onclick='ClickRemove()' name='add' type='button' value='Remove Item'>
<div>
<select id='listBox2' class='form-group percent-100' size='5'></select>
</div>
";
echo "<script>";
include 'bstest.js';
echo "</script>";
And, this is my JS (bstest.js).
function ClickAdd()
{
// get the 'left' listbox.
var e = document.getElementById('listBox1');
// get the text and value of selected item.
var eText = e.options[e.selectedIndex].text;
var eVal = e.value;
// create the new element
var opt = document.createElement('option');
opt.text = eText;
opt.value = eVal;
// add it to the 'right' listbox.
document.getElementById('listBox2').options.add(opt);
// now remove it from the 'left' list.
value = e.selectedIndex;
e.removeChild(e[value]);
sortSelect(e);
}
function ClickRemove()
{
// get the 'right' listbox.
var e = document.getElementById('listBox2');
// get the text and value of selected item.
var eText = e.options[e.selectedIndex].text;
var eVal = e.value;
// create the new element
var opt = document.createElement('option');
opt.text = eText;
opt.value = eVal;
// add it to the 'left' listbox.
document.getElementById('listBox1').options.add(opt);
// now remove it from the 'right' list.
value = e.selectedIndex;
e.removeChild(e[value]);
sortSelect(e);
}
function sortSelect(selectToSort)
{
//selectToSort = document.getElementById('listBox1'); // works. If I comment it, it doesn't work.
var arrOptions = [];
for (var i = 0; i < selectToSort.options.length; i++)
{
arrOptions[i] = [];
arrOptions[i][0] = selectToSort.options[i].value;
arrOptions[i][1] = selectToSort.options[i].text;
arrOptions[i][2] = selectToSort.options[i].selected;
}
arrOptions.sort();
for (var i = 0; i < selectToSort.options.length; i++)
{
selectToSort.options[i].value = arrOptions[i][0];
selectToSort.options[i].text = arrOptions[i][1];
selectToSort.options[i].selected = arrOptions[i][2];
}
return;
}
There is a select with a list of countries. Choosing a country it should create new select with a list of cities from this country.
var selectCountries = document.getElementById("countries");
var options = selectCountries.options;
for( var i = 0; i < options.length; i++ ){
options[i].addEventListener("click",funct )
}
function funct(){
var mainDiv = document.getElementById("main");
var newCities = document.createElement("select");
main.appendChild(newCities);
var newOptions = document.createElement("option");
newCities.appendChild(newOptions);
}
<div id="main"> <select id="countries"> <option>France</option> <option>Germany</option> </select> </div>
My suggestion: create one <select id="cities"> then hide it, then we don't need to care about whether <select id="cities"> exists when selecting one country.
For DOM, you need to loop options under <select id="countries"> to check which option is selected. so I created one function=getSelectedValue
And I created one var citiesConfigs to save all cities, then when selecting one city, pull out all cities under the selected county.
Finally, in function=funct,
get selected option for <select id="countries">
get all cities under the selected country, loop them to create <option> then append to <select id="cities">
finally, show up <select id="cities">
var selectCountries = document.getElementById("countries");
var options = selectCountries.options;
for( var i = 0; i < options.length; i++ ){
options[i].addEventListener("click",funct )
}
var citiesConfigs = {'france': ['CityA', 'CityB'], 'germany':['CityC','CityD']}
function getSelectedValue(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].value;
}
function funct(){
var mainDiv = document.getElementById("main");
var selectedCity = document.getElementById("cities")
selectedCity.innerHTML = ''
citiesConfigs[getSelectedValue('countries')].forEach(function(city){
let newOption = document.createElement("option");
newOption.value = city
newOption.text = city
selectedCity.appendChild(newOption);
})
selectedCity.style.display = ''
}
<div id="main"> <select id="countries"> <option value="france">France</option> <option value="germany">Germany</option> </select>
<select id="cities" style="display:none"></select>
</div>
I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE
I assumed that the my select state dropdown box would automatically display "select state" However, this did not work as I had expected. The dropdown box is empty until I choose a country and only then will the state dropdown box display "select state. How can I set my state dropdown box to "select state" by default?
function populateStates(countryElementId, stateElementId) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length = 0; //
stateElement.options[0] = new Option('Select State', '');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i = 0; i < state_arr.length; i++) {
if (state_arr[i] != "") {
stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
}
}
}
function populateCountries(countryElementId, stateElementId) {
// given the id of the <select> tag as function argument, it inserts <option> tags
var countryElement = document.getElementById(countryElementId);
jQuery("#" + countryElementId + " option").remove();
jQuery("#" + countryElementId).append("<option value=\"\">USA</option>");
for (var i = 0; i < country_arr.length; i++) {
countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
}
// Assigned all countries. Now assign event listener for the states.
if (stateElementId) {
countryElement.onchange = function() {
populateStates(countryElementId, stateElementId);
jQuery("#" + stateElementId + " option:eq(0)").attr("selected", "selected");
jQuery("#" + stateElementId).val("").change();
if (jQuery("#" + countryElementId).val() == "USA") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "5");
} else if (jQuery("#" + countryElementId).val() == "Canada") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "6");
} else {
jQuery("#Zip_Postal_Code__c").removeAttr("maxlength");
}
};
}
}
You can just use the default state dropdown html to contain only one option: Select State. e.g. in the html
<select id="state_select">
<option value="">Select State</option>
</select>
To prevent the first option from being selected:
<select>
<option value="" disabled selected hidden>Select State</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
</select>