Changing select content - javascript

I am back. How am I suppose to change a select content if I choose an option of other select. This is my JSFiddle. What I want is that if I select the 'mes' = 2 option (february). It shows me only 28 days on the 'dia' select (days). I don't know how to refer when the number 2 is selected so I can build a if structure. Thx in advance, my english is not the best... (I don't wanna use JQuery)
This is my whole HTML:
<p>Dia
<select name="dia" id="dia"></select>Mes
<select name="mes1" id="mes"></select>Año
<select name="año" id="año"></select>
</p>
<p>
<input type="text" name="txtFecha1" id="txtFecha1" disabled/>
<input type="submit" name="capturar" id="capturar" value="Capturar" onclick="capturar()" />
</p>
<p>
<input type="text" name="txtFecha2" id="txtFecha2" disabled/>
<input type="submit" name="capturar2" id="capturar2" value="Capturar" onclick="capturar()" />
</p>
<p>
<input type="submit" name="diferencia" id="diferencia" value="Diferencia" onclick="diferencia()" />
</p>
<p id="pParrafo">Dias entre las fechas:</p>
onClick functions are not programmed yet.
This is the JS:
var mes = new Array();
for (i = 1; i <= 12; i++) {
mes[i] = i;
}
var seleccionar = document.getElementById('mes');
for (var i = 1; i < mes.length; i++) {
var option = document.createElement('option');
option.innerHTML = mes[i];
option.value = mes[i];
seleccionar.appendChild(option);
}
var año = new Array();
for (i = 1950; i <= 2014; i++) {
año[i] = i;
}
var seleccionar = document.getElementById('año');
for (var i = 1950; i < año.length; i++) {
var option = document.createElement('option');
option.innerHTML = año[i];
option.value = año[i];
seleccionar.appendChild(option);
}

Here's a simple example of how I'd do it: add and remove options from the days select based on the year and month selected. It doesn't create or destroy options, it just moves them around.
It's less code and more efficient than alternatives.
<script>
// Simple function to return days in month given year and month
// Month is calendar number, e.g. 1 = jan, 2 = feb, etc.
function daysInMonth(year, month) {
return new Date(year, month, 0).getDate();
}
// Update the number of options in the day select
var updateDay = (function() {
// Document fragment to store spare options
var frag = document.createDocumentFragment();
return function(control) {
// Get a reference to the form and day select
var form = control.form;
var daySelect = form.day;
// Get days in month based on year and month selected
var days = daysInMonth(form.year.value, form.month.value);
// Remove or restore days to correct number
while(daySelect.options.length != days) {
daySelect.options.length > days? frag.appendChild(daySelect.lastChild) :
daySelect.appendChild(frag.lastChild);
}
}
}());
</script>
<!-- Simple date selector -->
<form>
Year: <select name="year" onchange="updateDay(this)">
<option value="2010">2010
<option value="2011">2011
<option value="2012">2012
<option value="2013">2013
<option value="2014">2014
</select>
Month: <select name="month" onchange="updateDay(this)">
<option value="1">Jan
<option value="2">Feb
<option value="3">Mar
<option value="4">Apr
<option value="5">May
<option value="6">Jun
<option value="7">Jul
<option value="8">Aug
<option value="9">Sep
<option value="10">Oct
<option value="11">Nov
<option value="12">Dec
</select>
Day: <select name="day">
<script>
// Saves on markup...
for (var i=1; i<32; i++) {
document.write('<option value="' + i + '">' + i + '<\/option>');
console.log(i);
}
</script>
</select>
</form>

youcan set filldia function on change of month select element
try this code :
HTML :
<select name="mes1" id="mes" onchange="fillDia(this)"
Javascript
// generate dia items
var dia = new Array();
fillDia(document.getElementById('mes'));
function fillDia(opt) {
// empty dia select element options
document.getElementById('dia').options.length = 0;
var maxDays = 31;
//alert (opt.value);
if (opt.value == '2') maxDays = 28; //feburary
if (opt.value == '4' || opt.value == '6' || opt.value == '9' || opt.value == '11') maxDays = 30; //april , june , september , november
for (i = 1; i <= maxDays; i++) {
dia[i] = i;
}
//se guarda el select dia
var dias = document.getElementById('dia');
//generar select para dia
for (var i = 1; i <= maxDays; i++) {
var option = document.createElement('option');
option.innerHTML = dia[i];
option.value = dia[i];
dias.appendChild(option);
}
}
JSFIDDLE DEMO

Related

Why The Select Option Didn't Showing Number?

i have some problems. Where my stock produk size is "100-199" The Select Option just showing this :
If in my product have stock is 1-99 and 200-999 i didn't get this error. The select option is fine and showing a number. In my case stok s and stok m the select option showing the number.
This my db :
This is my Controller :
$data['stock'] = $this->Product_model->get_product_all($id);
This is my Models :
public function get_product_all($id){
$this->db->select('products_shirt.*');
$this->db->from('products_shirt');
$query = $this->db->get();
return $query->row_array();
This is view code :
<select name="product_size" id="product_size" class="form-control" onchange="proses_stock()" style="width:95%">
<option value="0">Select Size:</option>
<option value="stock_s">s</option>
<option value="stock_m">m</option>
<option value="stock_l">L</option>
</select>
<select name="product_stock" id="product_stock" class="form-control" style="width:95%">
<option value="0">0</option>
</select>
This is JavaScript Code :
function proses_stock() {
var product_stock = document.getElementById("product_size").value;
var stocks = "<?php echo $stock['stock_s'];?>";
var stockm = "<?php echo $stock['stock_m'];?>";
var stockl = "<?php echo $stock['stock_l'];?>";
if(product_stock == "0") {
document.getElementById("product_stock").innerHTML = "<option value='0'>0</option>";
} else if (product_stock == "stock_s") {
disable_values(stocks); //add till this option
} else if (produk_stock == "stock_m") {
disable_values(stockm); //add till this option
} else {
//if large size select
//do somthing ..
disable_values(stockl); //add till this option
}
}
function disable_values(end) {
var gets = document.getElementById("product_stock");
var data="";
var limbuy = "<?php echo $stock['minorder'];?>";
var limbuys = 4;
//loop through all options
//for (var i = limbuys; i <= end; i++) {
for (var i = limbuy; i <= end; i++) {
//append options
data +="<option value="+i+">"+i+"</option>";
}
//add data to select box
gets.innerHTML= data;
}
When i'm use var limbuys so var i = limbuys; i get the normal way, and if i change with var limbuy so var i = limbuy; and get data number from database minorder i'm find this problem. And the problem just if example "in stok L just have 100-199 stock" i get this error(look picture). and if i pick size s (max stock 80) or size m (max stock 250) and im using limbuy its fine, why?
I'm using codeigniter with bootsrap. Thanks for help
This is happen because your limbuy and your end is a string
you can try use
for (var i = parseInt(limbuy); i <= parseInt(end); i++) {
data +="<option value='"+i+"'>"+i+"</option>";
}
<div class="form-group form-md-line-input form-md-floating-label">
<select class="form-control edited" name="rating" id="form_control_1">
<option value="<?php echo $manage->rating;?>"><?php echo $manage->rating;?></option>
<option value="0.5">0.5</option>
<option value="1">1</option>
<option value="1.5">1.5</option>
</select>
</div>

How to select maximum date from select box show alert message in Js

In the below snippet, the maximum date is 29-July-2017. If I select the maximum date we should display an alert box. Is it possible using Javascript or jQuery?
Note: Options display in random order.
HTML:
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>
You can try something like this:
Logic:
Create a variable that will either hold value or text(in below sample) of max date.
Then add an eventListener to check the necessary attribute on change.
If this attribute is same as Max computed in step 1, alert the user.
Note: Both the approaches assumes that there will be no dynamic elements and so the computation of max date is done beforehand on document.ready. Also, I'm keeping value or text in variable. This will allow us to bypass the step to create date on every change.
Approach with Text
$(function(){
var maxValue = null;
function computeMaxValue(arr){
arr.reduce(function(_max, cur){
var t = new Date(cur).getTime();
if(t > _max) {
_max = t;
maxValue = cur;
}
return _max;
}, 0)
}
var dates = $('#period option').map(function(){ return $(this).text() }).get();
computeMaxValue(dates);
$('#period').on('change', function(){
var text = $('option:selected', this).text();
if(text === maxValue){
console.log('You have selected Max value');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>
Approach with Value
$(function(){
var maxValue = null;
function computeMaxValue(selector){
var temp = 0;
$(selector).each(function (index, el){
var time = new Date(el.textContent).getTime();
if(time >= temp) {
temp = time;
maxValue = el.value;
}
})
}
computeMaxValue('#period option');
$('#period').on('change', function(){
if(this.value === maxValue){
console.log('You have selected Max value');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>
Sample with 1 option
$(function(){
var maxValue = null;
function computeMaxValue(selector){
var temp = 0;
$(selector).each(function (index, el){
var time = new Date(el.textContent).getTime();
if(time >= temp) {
temp = time;
maxValue = el.value;
}
})
}
computeMaxValue('#period option');
$('#period').on('change', function(){
if(this.value === maxValue){
console.log('You have selected Max value');
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option>--Select Period--</option>
<option value="5">23-July-2017</option>
</select>
Hope the below code helps
<!DOCTYPE html>
<html>
<head>
<title> Stack Overflow Question </title>
<style>
</style>
</head>
<body>
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$('#period').on('change',function(){
//Array to Store the dates from the options
var datesArr = [];
//Get the date from the Selected option
var d = new Date($('#period option:selected').text()).getDate();
//Pushing the dates to the Array
$('#period option').each(function(){
var d = new Date($(this).text());
datesArr.push(d.getDate());
});
//Getting the Max value from the Array
var max = Math.max(...datesArr);
//Converting to integers
d = parseInt(d);
max = parseInt(max);
//Comparing
if(d == max){
alert("Selected the Maximum Date");
}
});
</script>
</body>
</html>
Try Below Code:
$("#period").change(function(){
var selectedValue = $(this).find("option:selected").text();
var data = selectedValue.split("-");
var month = new Date(Date.parse(data['1']+data['0'], data['2'])).getMonth();
var selectedDate = new Date(data['2'],month,data['0']);
var dates = [];
$("#period").find("option").each(function(e){
var currentText = $(this).text();
var currenData = currentText.split("-");
var currentMonth = new Date(Date.parse(data['1']+data['0'], data['2'])).getMonth();
dates.push(new Date(currenData['2'],currentMonth,currenData['0']));
});
var maxDate=new Date(Math.max.apply(null,dates));
if(selectedDate.getTime() === maxDate.getTime()){
alert(maxDate);
}
});
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Turn options into ms and get the max value, then check if the selected date is as same as the max value.(use pure js)
var periodSelector = document.getElementById('period');
var options = periodSelector.options;
periodSelector.onchange = function(e) {
// get the selected date and convert it to ms
var selectedIndex = this.selectedIndex;
var selectedDate = new Date(options[selectedIndex].text).valueOf();
// convert all date to ms and get the max date
var maxDate = Array.prototype.reduce.call(options, function(maxValue, curValue) {
return Math.max(new Date(curValue.text), maxValue);
}, 0);
// check if selected date is same as max date
if (selectedDate === maxDate) {
alert('Max Date is selected');
}
};
<select id="period" name="PeriodCollection" style="border-radius: 4px; ">
<option value="3">10-July-2017</option>
<option value="12">15-July-2017</option>
<option value="9">29-July-2017</option>
<option value="5">23-July-2017</option>
</select>

Select list does not change selected item DHTML

I'm starting to develop websites (learning from 0). Of course, I apologize for my healthy ignorance (and my english level).
I have 3 select in descending order: the 1st one contains a list of options that are loaded from a database (for now, I only load from HTML). Depending on the option selected, the 2nd select will be loaded with its options and so on until a 3rd select. The problem itself is solved, but when you want to select the options already loaded in the 2nd select, do not "click" on them. Only allows you to select the first one option. Here I leave the code to see if anyone can find any possible solution (and a lot of errors ^^).
var carsAndModels = {};
carsAndModels['Volvo'] = ['V70', 'XC60'];
carsAndModels['Volkswagen'] = ['Golf', 'Polo'];
carsAndModels['BMW'] = ['M6', 'X5'];
var speedsAndModels = {};
speedsAndModels['V70'] = ['150km/h', '180km/h'];
speedsAndModels['XC60'] = ['160km/h', '190km/h'];
speedsAndModels['Golf'] = ['170km/h', '190km/h'];
speedsAndModels['Polo'] = ['180km/h', '200km/h'];
speedsAndModels['M6'] = ['190km/h', '2000km/h'];
speedsAndModels['X5'] = ['200km/h', '210km/h'];
function ChangeCarList() {
var carList = document.getElementById('car');
var modelList = document.getElementById('carmodel');
var speedList = document.getElementById('speed');
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
speedList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i+1);
modelList.options.add(car);
}
}
ChangeModelList();
}
function ChangeModelList() {
var modelListM = document.getElementById('carmodel');
var speedListM = document.getElementById('speed');
var indMod = modelListM.selectedIndex;
var selMod = modelListM.options[indMod].text;
while (speedListM.options.length) {
speedListM.remove(0);
}
var speeds = speedsAndModels[selMod];
if (speeds) {
for (i = 0; i < speeds.length; i++) {
var speed = new Option(speeds[i], i+1);
speedListM.options.add(speed);
}
}
}
<div class="">
<div class="">
<span>Select the brand</span><hr>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Select --</option>
<option value="Volvo">Volvo</option>
<option value="Volkswagen">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
</div>
<div class="">
<span>Select the model</span><hr>
<select id="carmodel" onchange="ChangeCarList()"></select>
</div>
<div class="">
<span>Select the speed control</span><hr>
<select id="speed"></select>
</div>
</div>
question: How to call the functions ("ChangeCarList" & "ChangeModelList") through the standard W3Schools in an external file?
Thank you very much :).
The reason it is not working is because you are removing the options on selecting a different option. You need to remember the selected option in index like below. You may have to tidy up your solution even more but this solution will let select other options.
Notice this added part in solution I propose.
var index;
if (value) {
index = modelList.selectedIndex;
}
Here old index is being remembered. Here the option is selected based on remembered index, once you are done with adding options.
modelList.selectedIndex = index;//<----This also is required
var carsAndModels = {};
carsAndModels['Volvo'] = ['V70', 'XC60'];
carsAndModels['Volkswagen'] = ['Golf', 'Polo'];
carsAndModels['BMW'] = ['M6', 'X5'];
var speedsAndModels = {};
speedsAndModels['V70'] = ['150km/h', '180km/h'];
speedsAndModels['XC60'] = ['160km/h', '190km/h'];
speedsAndModels['Golf'] = ['170km/h', '190km/h'];
speedsAndModels['Polo'] = ['180km/h', '200km/h'];
speedsAndModels['M6'] = ['190km/h', '2000km/h'];
speedsAndModels['X5'] = ['200km/h', '210km/h'];
function ChangeCarList(value) {
var carList = document.getElementById('car');
var modelList = document.getElementById('carmodel');
var speedList = document.getElementById('speed');
var selCar = carList.options[carList.selectedIndex].value;
var index;
if (value) {
index = modelList.selectedIndex;
}
while (modelList.options.length) {
modelList.remove(0);
speedList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i + 1);
modelList.options.add(car);
}
}
modelList.selectedIndex = index;
ChangeModelList();
}
function ChangeModelList() {
var modelListM = document.getElementById('carmodel');
var speedListM = document.getElementById('speed');
var indMod = modelListM.selectedIndex;
var selMod = modelListM.options[indMod].text;
while (speedListM.options.length) {
speedListM.remove(0);
}
var speeds = speedsAndModels[selMod];
if (speeds) {
for (i = 0; i < speeds.length; i++) {
var speed = new Option(speeds[i], i + 1);
speedListM.options.add(speed);
}
}
}
<div class="">
<div class="">
<span>Select the brand</span>
<hr>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Select --</option>
<option value="Volvo">Volvo</option>
<option value="Volkswagen">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
</div>
<div class="">
<span>Select the model</span>
<hr>
<select id="carmodel" onchange="ChangeCarList(this.value)"></select>
</div>
<div class="">
<span>Select the speed control</span>
<hr>
<select id="speed"></select>
</div>
</div>

Display Day ,Month and Year in place of current day,month and year

I have the following javascript code which displays current day, month and year in the dropdown. The code is as follows:
var monthtext=['January','February','March','April','May','June','July','August','September','October','November','December'];
function populatedropdown(dayfield, monthfield, yearfield) {
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=0; i<31; i++) {
dayfield.options[i]=new Option(i+1)
}
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++) {
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
}
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=today.getFullYear()
for (var y = 0; y < 100; y++) {
yearfield.options[y] = new Option(thisyear, thisyear)
thisyear -= 1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
<script type="text/javascript">
//populatedropdown(id_of_day_select, id_of_month_select, id_of_year_select)
window.onload=function(){
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
}
</script>
<select id="daydropdown" name="D-DOB"></select>
<select id="monthdropdown" name="M-DOB"></select>
<select id="yeardropdown" name="Y-DOB"></select>
I wish to display "Select Day", "Select Month" and "Select Year" as default values in place of current values like:
<option value="">Select Day</option>
Fiddle: https://jsfiddle.net/u2m243qf/1/
EDIT:
Resolved by myself:
I have restructured my code and arrived at a simpler solution. New Fiddle at:
https://jsfiddle.net/u2m243qf/9/
If I understood your request you want to display a default value in your options? If so, just do:
<option value="x" selected="your-selected"> Select day </option>
You can also find a deeper discussion on the topic here:
How can I set the default value for an HTML <select> element?
... and in JS it is:
dayfield.value = "Select Day";

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

Categories