I'm writing a small php page with 2 form:
<div class="input-field col s12">
<select id="select1">
<option value="" disabled selected>Choose your option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="select2">
<option value="" disabled selected>Choose your option</option>
<option rel="1" value="11">Option 11</option>
<option rel="1" value="12">Option 12</option>
<option rel="2" value="21">Option 21</option>
<option rel="2" value="22">Option 22</option>
<option rel="3" value="31">Option 31</option>
<option rel="3" value="32">Option 32</option>
</select>
</div>
After I select the first select form, I want that only the related values are showed in the second.
My js is:
$(function() {
$("#select1").on('change', function() {
$subcat = $("#select2");
var _rel = $(this).val();
$subcat.find("[rel="+_rel+"]").show();
$subcat.prop("disabled",false);
// re-initialize material-select
$('#select2').material_select();
});
});
I also try with
var selectobject=document.getElementById("select2")
for (var i=0; i<selectobject.length; i++)
{
if (selectobject.options[i].value == 'xxxx' )
{
selectobject.remove(i);
}
}
But I need the name option, not the value.
$(function(){
$('#select1').on('change', function(){
var val = $(this).val();
var sub = $('#select2');
$('option', sub).filter(function(){
if ($(this).attr('rel') === val) {
if ($(this).parent('span').length) {
$(this).unwrap();
}
} else {
if (!$(this).parent('span').length) {
$(this).wrap( "<span>" ).parent().hide();
}
}
});
});
});
I don't see which options at the second form corresponding to the first, however, try populating the second select rather than removing items from it. like:
<select id="select1" onchange="myfunction(this.value)">
<script>
function myfunction(opt){
var $Select2 = $('#select2');
var option1 = [
{
"name": "option description",
"value": "1"
}, {
"name": "option description",
"value": "1"
}]
var option2 = [
{
"name": "option description",
"value": "1"
}, {
"name": "option description",
"value": "1"
}]
if(opt === option1){
$.each(option1, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.name
}));
});
}
if(opt === option2){
$.each(option2, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.name
}));
});
}
}
</script>
Related
Can anyone teach me how can I update json value using the the dropdown list.
In JavaScript
HTML:
<select id="currency" onchange="getSelectValue();">
<option value="Singapore Dollar">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="Malaysia Riggit">Malaysia Riggit</option>
</select>
JSON :
{
"products": [
{
"name": "Apple",
"price": "2.50",
"code": "SGD"
},
{
"name": "Orange",
"price": "2.50",
"code": "SGD"
}
]
}
You can create a select in javascript like this, focus on the <script />
<!DOCTYPE html>
<html lang="en">
<head>
<title>Javascript - Select</title>
</head>
<body>
<div id="main"></div>
</body>
<script>
const {products} = JSON.parse('{ "products": [ { "name": "Apple", "price": "2.50", "code": "SGD" }, { "name": "Orange", "price": "2.50", "code": "SGD" } ] }');
const select = document.createElement("select");
select.id = 'currency';
select.onchange = ({target: {value}}) => console.log(value);
products.forEach(({code, name}) => {
const option = document.createElement("option");
option.label = name;
option.value = code;
select.appendChild(option);
});
const main = document.getElementById('main');
main.appendChild(select);
</script>
</html>
EDIT:
Add the "value" as a param of the function
<select id="currency" onchange="getSelectValue(value)">
<option value="SGD">Singapore Dollar</option>
<option value="USD">USD</option>
<option value="MR">Malaysia Riggit</option>
</select>
and the function definition should look like this:
const getSelectValue = (selectedValue) => {
console.log(selectedValue);
// Your code...
};
Here is the code sample.
var json=JSON.parse( "Your json which you mentioned above");
var products= json.products;
string selectlist="";
if(products.length>0)
{
selectlist += "<select>";
for(var i = 0; i < products.length; i++) {
var currency = json[i];
selectlist += "<option value="+currency.code+"> "+currency.code+" </option>";
}
selectlist += "</select>"
if("body").append(selectlist);
}
I have this nested optgroup:
<select>
<optgroup label="A">
<optgroup label="B">
<option>C</option>
<option>D</option>
<option>G</option>
</optgroup>
<optgroup label="J">
<option>K</option>
<option>L</option>
<option>M</option>
</optgroup>
</optgroup>
</select>
but the result is:
You can use Select from react-select.
import Select from "react-select";
const options = [
{
label: "A",
options: [
{
label: "B",
options: [
{
label: "C",
value: 1
},
{
label: "D",
value: 2
},
{
label: "G",
value: 3
}
]
},
{
label: "J",
options: [
{
label: "K",
value: 4
},
{
label: "L",
value: 5
},
{
label: "M",
value: 6
}
]
}
]
}
];
export const NestedOptGroup = () => <Select name="options" options={options} />
There is a working example of this react-select feature: https://codesandbox.io/s/react-codesandboxer-example-8xxyx?file=/index.js
Source: How can I create nested option groups in React Select (V2)?
you can use only 1 sub group, like this
<select>
<optgroup label="B">
<option>C</option>
<option>D</option>
<option>G</option>
</optgroup>
<optgroup label="J">
<option>K</option>
<option>L</option>
<option>M</option>
</optgroup>
</select>
if you wish add more subgroups you need to hack the identation
here have other answers for this:
Nesting optgroups in a dropdownlist/select
How can I make it so when I select an option it will only populate that one area?
I only want the specific places in that area.
example picture.]
Example of the output (1)
Example of the output (2)
this is the json code that I want to have a function and connect the two or more files.
json file 1
{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}
json file 2
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000000"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000000"
}
here is the code
html part
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>
<script>
$(function(){
let regionOption;
let provinceOption;
//FOR REGION
$.getJSON('regions.json', function(result){
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region){
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
});
//FOR PROVINCE
$('#region').change(function(){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
});
});
</script>
my failed attempt is this part :
$('#region').change(function(){
if($(this).val() === $(this).val()){
$.getJSON('provinces.json', function(result){
provinceOption += `<option value="">Select Province</option>`;
$.each(result, function(region, province){
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
});
}
});
You can use .filter() to filter your json return inside ajax then inside this compare value of select-box with all values of region if they matches get that data . Finally loop through filter datas and show them inside your select-box.
Demo Code :
//just for demo :)
var result = [{
"code": "010000000",
"name": "Ilocos Region",
"altName": "Region I"
}, {
"code": "010000002",
"name": "Ilocos Region2",
"altName": "Region 2"
}]
var json2 = [
{
"code": "012800000",
"name": "Ilocos Norte",
"altName": null,
"region": "010000000"
},
{
"code": "012900000",
"name": "Ilocos Sur",
"altName": null,
"region": "010000000"
},
{
"code": "013300000",
"name": "La Union",
"altName": null,
"region": "010000002"
},
{
"code": "015500000",
"name": "Pangasinan",
"altName": null,
"region": "010000002"
}
]
$(function() {
let regionOption;
let provinceOption;
//FOR REGION
/* $.getJSON('regions.json', function(result) {*/
regionOption += `<option value="">Select Region</option>`;
$.each(result, function(i, region) {
regionOption += `<option value='${region.code}'> ${region.altName}</option>`;
});
$('#region').html(regionOption);
/* });*/
$('#region').change(function() {
var values = $(this).val()
var provinceOption = ""
/*$.getJSON('provinces.json', function(json2) {*/
//filter your json return..
var items = $(json2)
.filter(function(i, n) {
return n.region === values; //get value where region is same
});
provinceOption += `<option value="">Select Province</option>`;
//loop through dates
$.each(items, function(region, province) {
provinceOption += `<option value='${province.name}'> ${province.name}</option>`;
});
$('#province').html(provinceOption);
/* });*/
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="container form-group" style="width:600px; margin-top: 10vh">
<form action="" method="GET" id="addform">
<div class="form-group">
<select name="region" id="region" class="form-control input-sm" required>
<option value="">Select Region</option>
</select>
</div>
<div class="form-group">
<select name="province" id="province" class="form-control input-sm" required>
<option value="">Select Province</option>
</select>
</div>
</form>
</div>
So, I'm trying to fill three separate dropdown menus (could end up being more) with objects pulled from different JSON files depending on the selection from each dropdown. So first selection fills the second one, and so on.
These are the dropdown menus:
<form>
<div>
<select id="level1">
<option selected value="base">Please select one</option>
<option value="first-option">First one</option>
<option value="second-option">Second one</option>
</select>
</div>
<div>
<select id="level2" class="form-control">
<option selected value="base">Please select one</option>
</select>
</div>
<div>
<select id="level3" class="form-control">
<option selected value="base">Please select one</option>
</select>
</div>
<div id="submit">
<button type="submit">Go</button>
</div>
</form>
This is a sample JSON file:
{
"first_option": {
"me": "first_option",
"COD_REF": "MX09017CL01AP",
"TITLE": "First Option",
"children": {
"child01": {
"me": "child01",
"COD_REF": "001",
"TITLE": "Child 1",
"children": {
"grandchild01": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
},
"grandchild02": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
}
}
}
},
"child02": {
"me": "child02",
"COD_REF": "002",
"TITLE": "Child 2",
"children": {
"grandchild01": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
},
"grandchild02": {
"me": "grandchild01",
"TITLE": "Grandchild 1"
}
}
},
}
}
The solution I came up with works just fine. The thing is I could probably do with some iteration, I just don't know how to do it. Here's an abridged version of what I have:
var vals = [];
var $level1 = $("#level1");
var $level2 = $("#level2");
var $level3 = $("#level3");
function generateTable(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
};
function generateTable2(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
}
function generateTable3(info) {
$(".COD_REF").innerHTML(info.COD_REF);
$(".TITLE").innerHTML(info.TITLE);
}
//first dropdown
$("#level1").change(function () {
var $dropdown = $(this);
var key = $dropdown.val();
function generateDropdown(vals) {
$level2.append("<option selected value=\"base\">Please select one</option>");
$.each(vals, function (index, value) {
$level2.append("<option value=\"" + value.me + "\">" + value.TITLE + "</option>");
});
};
switch (key) {
case 'first_option':
$.getJSON("recursos/json/ajsonfile.json", function (data) {
$level2.empty();
vals = data.first_option.children;
generateDropdown(vals)
$("#first-table").removeClass("d-none");
$("#first-table").addClass("d-block");
info = data.first_option;
$(".first-title").innerHTML(info.TITLE);
generateTable(info);
});
break
case 'second_option':
$.getJSON("recursos/json/anotherjsonfile.json", function (data) {
$level2.empty();
vals = data.second_option.children;
generateDropdown(vals)
$("#first-table").removeClass("d-none");
$("#first-table").addClass("d-block");
info = data.second_option;
$(".first-title").innerHTML(info.TITLE);
generateTable(info);
});
break
case 'base':
$level2.empty();
vals = ['Please select one'];
$level2.append("<option>" + vals + "</option>");
$("#first-table").removeClass("d-block");
$("#first-table").addClass("d-none");
console.log(vals);
break
}
});
//second dropdown
$("#level2").change(function () {
var $dropdown = $(this);
var key = $dropdown.val();
function generateDropdown(vals) {
$level3.append("<option selected value=\"base\">Please select one</option>");
$.each(vals, function (index, value) {
$level3.append("<option value=\"" + value.yo + "\">" + value.TITLE + "</option>");
});
};
switch (key) {
case 'first-child':
$.getJSON("recursos/json/ajsonfile.json", function (data) {
$level3.empty();
vals = data.first_option.children.child01.children;
generateDropdown(vals)
$("#second-table").removeClass("d-none");
$("#second-table").addClass("d-block");
info = data.first_option.children.child01;
$(".second-title").innerHTML(info.TITLE);
generateTable2(info);
});
break
//second, third, fourth child options etc.
case 'base':
$level3.empty();
vals = ['Please select one'];
$level3.append("<option>" + vals + "</option>");
$("#cedula2").removeClass("d-block");
$("#cedula2").addClass("d-none");
console.log(vals);
break
}
});
//third dropdown
$("#level3").change(function () {
// I think you get the gist
});
Is it possible to do some iteration so I can fill all the dropdowns in just one loop?
I know that there are a lot of this questions being posted online but I still have difficulty finding what I need.
Currently I have found something that is doing 3 chained dropdown selection maximum. I needed to have 4 and I have tried editing the script but it's not working.
Below is the code that I have edited, is there anything wrong with my code?
<html>
<head>
<script type="text/javascript">
// State lists
var states = new Array();
states[0] = new Array('Alberta','British Columbia','Ontario');
states[1] = new Array('Baja California','Chihuahua','Jalisco');
states[2] = new Array('California','Florida','New York');
// Province lists
var provinces = new Array();
provinces[0] = new Array();
provinces[0][0] = new Array("Province1", "Province2");
// City lists
var cities = new Array();
cities[0][0] = new Array();
cities[0][0][0] = new Array('Edmonton','Calgary');
cities[0][0][1] = new Array('Victoria','Vancouver');
function setStates(){
cntrySel = document.getElementById('country');
stateList = states[cntrySel.selectedIndex];
changeSelect('state', stateList);
setProvinces();
}
function setProvinces(){
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
provinceList = provinces[cntrySel.selectedIndex][stateSel.selectedIndex];
changeSelect('province', provinceList);
setCities();
}
function setCities(){
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
provinceList = document.getElementById('province');
cityList = cities[cntrySel.selectedIndex][stateSel.selectedIndex][provinceList.selectedIndex];
changeSelect('city_town_district', cityList);
}
function changeSelect(fieldID, newList) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newList.length; i++) {
selectField.options[selectField.length] = new Option(newList[i], newList[i], newList[i]);
}
}
</script>
</head>
<body onload="setStates();">
<form name="test">
Country:
<select name="country" id="country" onchange="setStates();">
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
<option value="United States">United States</option>
</select>
<br>
State:
<select name="state" id="state" onchange="setProvinces();">
<option value="">Please select a State</option>
</select>
<br>
Province:
<select name="province" id="province" onchange="setCities();">
<option value="">Please select a Province</option>
</select>
<br>
City:
<select name="city_town_district" id="city_town_district">
<option value="">Please select a City</option>
</select>
</form>
</body>
</html>
Any help will be much appreciated! Thanks in advance!
Old question, one answer and everybody have to do this sometimes.
The year is 2018 and I find a easy way to do this. Easy to add, edit and receive data from server. Bye!
JSFiddle
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select name="slc1" id="slc1" onchange="_1sel();"></select>
<select name="slc2" id="slc2" onchange="_2sel();"></select>
<select name="slc3" id="slc3" onchange="_3sel();"></select>
<select name="slc4" id="slc4"></select>
<script>
//just call the method when the select change
var slc1 = document.getElementById("slc1");
var slc2 = document.getElementById("slc2");
var slc3 = document.getElementById("slc3");
var slc4 = document.getElementById("slc4");
var dataObj = {//is a valid json
"brazil": {
"sp": {
"sp1": ["sp1A", "sp1B"],
"sp2": ["sp2A"]
},
"mg": {
"mg1": ["mg1A", "mg1B"],
"mg2": ["mg2A", "mg1B"]
},
"rj": {
"rj1": ["rj1A", "rj1B", "rj1C"],
"rj2": ["rj2A", "rj1B"]
}
},
"usa": {
"ny": {
"ny1": ["ny1A","ny1B","ny1C"],
"ny2": ["ny2A"]
},
"tx": {
"tx1": ["tx1A"]
}
},
"uk": {
"ld": {
"ld1": ["ld1A","ld1B","ld1C"],
"ld2": ["ld2A"]
},
"hm": {
"hm1": ["hm1A", "hm1B"]
}
}
}
let ctrs = Object.keys(dataObj);//countries - Object.keys return an array
cmo(ctrs, slc1);//push values to select one
_1sel();//call the first method of chain
//slc1.value = "usa"
//slc1.dispatchEvent(new Event('change'));
function _1sel() {
slc2.innerHTML = "";//clear the target select
let cities = Object.keys(dataObj[slc1.value]);//get the cities from country as array
cmo(cities, slc2);//push values to select two
_2sel();//call the second method of chain
}
function _2sel() {
slc3.innerHTML = "";//clear
let zones = Object.keys(dataObj[slc1.value][slc2.value]);//get the zones from country and city as array
cmo(zones, slc3);//push values to select three
_3sel();//call the third method of chain
}
function _3sel() {
slc4.innerHTML = "";//clear
let staffs = dataObj[slc1.value][slc2.value][slc3.value];//no Obj.keys here, just get the array of values
cmo(staffs, slc4);//push values to select four
}
function cmo(arr, s) {//create options and add to select
arr.forEach(o => {
let opt = document.createElement("option");
opt.value = o;
opt.innerHTML = o;
s.add(opt);
});
}
</script>
</body>
</html>
This is not perfect by any means but it should get you going. Instead of having unrelated arrays I suggest you use some object oriented principles. I've chosen to use JSON to describe the relationships in the data. The other advantage to using JSON is that many server side languages have JSON serializers available to them.
I have kept as much of your code as possible so there is some familiarity for you. However inline event handling is not considered best practice these days. You should look at Event Listeners/Handlers instead. Or if it was me I would be using jQuery as it irons out much of the cross browser issues you can come across.
/*Use JSON to describe data and its relationship*/
var countries = [{
"CountryName": "Canada",
"States": [{
"StateName": "British Columbia",
"Provences": [{
"ProvenceName": "BC P1",
"Cities": ["Vancouver"]
}, {
"ProvenceName": "BC P2",
"Cities": ["Whistler"]
}]
}, {
"StateName": "Ontario ",
"Provences": [{
"ProvenceName": "Ot 1",
"Cities": ["Ontario"]
}, {
"ProvenceName": "Ot 2",
"Cities": ["Toronto"]
}]
}]
}, {
"CountryName": "United States",
"States": [{
"StateName": "New York",
"Provences": [{
"ProvenceName": "NY P1",
"Cities": ["New York", "New Jersy"]
}, {
"ProvenceName": "NY P2",
"Cities": ["Buffalo"]
}]
}, {
"StateName": "California",
"Provences": [{
"ProvenceName": "South",
"Cities": ["Los Angeles", "San Dieago"]
}, {
"ProvenceName": "North",
"Cities": ["San Francisco"]
}]
}]
}];
var selectedCountry;
var selectedState;
var selectedProvence;
var stateList = document.getElementById("state");
var provenceList = document.getElementById("province");
var cityList = document.getElementById("city_town_district");
function setStates(selectedIndex) {
selectedCountry = countries[selectedIndex];
stateList.options.length = 0;
for (i = 0; i < selectedCountry.States.length; i++) {
stateList.options[stateList.length] = new Option(selectedCountry.States[i].StateName, selectedCountry.States[i].StateName, selectedCountry.States[i].StateName);
}
setProvinces(0);
}
function setProvinces(selectedIndex) {
selectedState = selectedCountry.States[selectedIndex];
console.log(selectedState)
provenceList.options.length = 0;
for (i = 0; i < selectedState.Provences.length; i++) {
provenceList.options[provenceList.length] = new Option(selectedState.Provences[i].ProvenceName, selectedState.Provences[i].ProvenceName, selectedState.Provences[i].ProvenceName);
}
setCities(0);
}
function setCities(selectedIndex) {
selectedProvence = selectedState.Provences[selectedIndex];
cityList.options.length = 0;
for (i = 0; i < selectedProvence.Cities.length; i++) {
cityList.options[cityList.length] = new Option(selectedProvence.Cities[i], selectedProvence.Cities[i], selectedProvence.Cities[i]);
}
}
Country:
<select name="country" id="country" onchange="setStates(this.selectedIndex);">
<option value="Canada">Canada</option>
<option value="United States">United States</option>
</select>
<br>State:
<select name="state" id="state" onchange="setProvinces(this.selectedIndex);">
<option value="">Please select a State</option>
</select>
<br>Province:
<select name="province" id="province" onchange="setCities(this.selectedIndex);">
<option value="">Please select a Province</option>
</select>
<br>City:
<select name="city_town_district" id="city_town_district">
<option value="">Please select a City</option>
</select>