Select list does not change selected item DHTML - javascript

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>

Related

How to make three level selection in html by using javascript

here two level selection are given with select tag , i want to make one more level by adding one more select tag.
if i selected madhya pradesh from first select tag then selected Rewa from second selection tag then option list should come into third selection tag with reference to Rewa such as Rewa appeared with respect to madhya pradesh.
tahshil[Rewa] =
{"Huzur","Hanumana","Teonthar","Mangawan","Jawa","Sirmour",
"Mauganj","Naigarhi","Semaria","Gurh","Raipur - Karchuliyan"}
<html>
<head>
<script type="text/javascript">
var countries = [ ];
countries["Madhya Pradesh"] = ["Indore","Jabalpur","Bhopal","Raisen","Rajgarh","Sehore","Vidisha","Morena","Sheopur","Bhind","Ashoknagar","Shivpuri","Rewa"];
countries["Uttar Pradesh"] = ["Allahabad","Moradabad","Ghaziabad","Azamgarh", "Lucknow","Kanpur Nagar","Jaunpur","Sitapur","Bareilly","Gorakhpur","Agra"];
function switchCountry(selCountry)
{
var citySel = selCountry.form.City;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = countries[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
</script>
</head>
<body>
<br>
<form>
<center>
<h3>Select State of shop : <select name="Country" onchange="switchCountry(this);">
<option value = "">Choose state</option>
<option value="mdp">Madhya Pradesh</option>
<option value="utp">Uttar Pradesh</option>
</select></h3>
<h3>Select District place : <select name="City">
<option>Choose City</option>
</select>
<h3>Select Tehsil place : <select name="Tehsil">
<option>Choose City</option>
</select>
</h3><br>
</center>
</form><br><br><br>
</body>
</html>
how to make third level selection ?
i made a solution for my question as follow:
<script type="text/javascript">
var countries = [ ];
countries["Madhya Pradesh"] = ["Indore","Jabalpur","Bhopal","Raisen","Rajgarh","Sehore","Vidisha","Morena","Sheopur","Bhind","Ashoknagar","Shivpuri","Rewa"];
countries["Uttar Pradesh"] = ["Allahabad","Moradabad","Ghaziabad","Azamgarh", "Lucknow","Kanpur Nagar","Jaunpur","Sitapur","Bareilly","Gorakhpur","Agra"];
var Tehsil = [ ];
Tehsil["Rewa"] = ["Huzur","Hanumana","Teonthar","Mangawan","Jawa","Sirmour", "Mauganj","Naigarhi","Semaria","Gurh","Raipur - Karchuliyan"];
function switchCountry(selCountry)
{
var citySel = selCountry.form.City;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = countries[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
function switchCountry1(selCountry)
{
var citySel = selCountry.form.Tehsil;
for ( var s = citySel.options.length-1; s > 0; --s )
{
citySel.options[s] = null;
}
var chosen = selCountry.options[selCountry.selectedIndex].text;
var cList = Tehsil[chosen];
if ( cList != null )
{
for ( var i = 0; i < cList.length; ++i )
{
citySel.options[i+1] = new Option(cList[i],cList[i]);
}
}
}
</script>
</head>
<body>
<br>
<form>
<center>
<h3>Select State of shop : <select name="Country" onchange="switchCountry(this);">
<option value = "">Choose state</option>
<option value="mdp">Madhya Pradesh</option>
<option value="utp">Uttar Pradesh</option>
</select></h3>
<h3>Select District place : <select name="City" onchange="switchCountry1(this);">
<option>Choose City</option>
</select>
<h3>Select Tehsil place : <select name="Tehsil">
<option>Choose Tehsil</option>
</select>
</h3><br>
</center>
</form><br><br><br>
</body>
</html>

How to dynamically create a dependent select list using one recursive function in pure javascript?

The following image shows the list structure that needs to be created. Using a recursive function it could be reused for n number of options. How can it be done?
Here is my Javascript code and below the HTML that I wrote:
var gender = ['male', 'female'];
var male = {
hair: ["Facial hair preferred?","Hair","No Hair"],
complexion: ["Preferred Complexion?","Pale","Dark"],
build: ["Build Type?","Strong","Weak"]
}
//Female Object
var female = {
hair: ["Hair Color?","Blonde","Brunette"],
height: ["Preferred Height?","Tall","Short"],
eyes: ["Preferred Eyes?","Green","Blue"]
}
function build(sel){
var selValue = sel;
if(selValue == gender[0]){
//console.log('male');
var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);
for(var i=0; i<male.hair.length; ++i){
var oEle = document.createElement('option');
if(i == 0){
oEle.setAttribute('disabled','disabled');
oEle.setAttribute('selected','selected');
}
var optionText = document.createTextNode(male.hair[i]);
oEle.appendChild(optionText);
document.getElementsByTagName('select')[1].appendChild(oEle);
}
}else{
//console.log('female');
var sEle = document.createElement('select');
document.getElementsByTagName('body')[0].appendChild(sEle);
for(var i=0; i<female.hair.length; ++i){
var oEle = document.createElement('option');
if(i == 0){
oEle.setAttribute('disabled','disabled');
oEle.setAttribute('selected','selected');
}
var optionText = document.createTextNode(female.hair[i]);
oEle.appendChild(optionText);
document.getElementsByTagName('select')[1].appendChild(oEle);
}
}
}
<body>
<h4>Select Sex </h4>
<select name="sel1" id="sel1" onchange="build(this.value)">
<option value="" selected disabled>Select Sex</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</body>
However I am stuck and unable to create any more. Moreover I am not able to create a recursive function that I can reuse for any data.
You can create an object with tree hierarchy like this:
function Node(msg, treeChildNodes)
{
var _node = this;
this.msg = msg;
this.treeChildNodes = treeChildNodes;
this.completed = function() {
console.log(this.value);
this.disabled = true;
if (_node.treeChildNodes[this.value])
_node.treeChildNodes[this.value].renderTo(_node.container);
else
{
console.log('the leaf! end test');
$("<button/>").text('Finish test').appendTo(_node.container);
}
};
this.renderTo = function(container) {
_node.container = container;
$("<p/>").text(_node.msg).appendTo(container);
var $select = $("<select/>").appendTo(container).change(this.completed);
$("<option/>").text("Not selected...").appendTo($select);
for (var childKey in this.treeChildNodes)
{
$("<option/>").text(childKey).appendTo($select);
}
};
}
var tree = new Node('Men or Women?', {
'M': new Node('Facial hair?', {
'Hair': new Node('Complexion', {
'D': null,
'L': null
}),
'No Hair': new Node('Build', {
'B': null,
'S': null
})
})
});
tree.renderTo('body');
select {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note that I haven't implemented women side of this tree, it is just an example, you can easily do it yourself :)
By the way, with this approach, your tree should not actually be a tree. For example, your test questions can split once, and then flock back into a single branch.

javascript - drop down display on the second field based on selection in first field

I have two fields customer category and customer type,
when I select one element in customer category , I need to display only a set of elements from customer type in the drop down and rest should not appear.
how do write it in javascript. Here is the one I tried but it doesnot yield proper result.
var custcategory = document.getElementById("custcatid");
var custtypes = document.getElementById('custtypeid').options;
alert('yes');
var n = custtypes.length;
var allowedtype;
if (custcategory.options[custcategory.selectedIndex].value == "ANALOGUE") {
alert('ANALOGUE');
allowedtype = 'CATV,CATV RURAL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "COMMERCIAL") {
alert('COMMERCIAL');
allowedtype = ' ,3ST HOTEL,4ST HOTEL,5ST HOTEL';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DAS") {
alert('DAS');
allowedtype = ' ,DAS PHASE1,DAS PHASE2,DAS PHASE3,DAS PHASE4';
}
else if (custcategory.options[custcategory.selectedIndex].value == "DTH") {
alert('DTH');
allowedtype = ' ,DTH';
}
var idx = 0;
for (var i = 0; i < n; i++) {
var type = custtypes[i].value;
var found = allowedtype.search(type);
if (found <= 0) {
custtypes[i].style.display = 'none';
}
else if (idx == 0) {
idx = 1;
document.getElementById('ctl00_uxPgCPH_custtype').selectedIndex = i;
}
}
alert('Done..!');
If I understand correctly, you are trying to filter a second select element based on what is selected in the first select element?
If so I put together the following snippet which might help you out. It can be probably be optimised further but it should help to get you started I feel.
(function () {
var CLASSES = {
categories: '.select__category',
types : '.select__types'
},
map = {
ANALOGUE: [
'CATV',
'CATV RURAL'
],
COMMERCIAL: [
'3ST HOTEL',
'4ST HOTEL',
'5ST HOTEL'
],
DAS: [
'DAS PHASE 1',
'DAS PHASE 2',
'DAS PHASE 3'
]
},
categorySelect = document.querySelector(CLASSES.categories),
typeSelect = document.querySelector(CLASSES.types),
filterTypes = function(val) {
// Based on a value filter the types select.
var opts = typeSelect.options,
allowedOpts = map[val];
typeSelect.value = allowedOpts[0];
for(var i = 0; i < opts.length; i++) {
if (allowedOpts.indexOf(opts[i].value) === -1) {
opts[i].hidden = true;
} else {
opts[i].hidden = false;
}
}
};
filterTypes(categorySelect.value);
categorySelect.addEventListener('change', function(e) {
filterTypes(this.value);
});
}());
<!DOCTYPE html>
<head></head>
<body>
<select id="categories" class="select__category">
<option value="ANALOGUE">Analogue</option>
<option value="COMMERCIAL">Commercial</option>
<option value="DAS">Das</option>
</select>
<select id="types" class="select__types">
<option value="CATV">Catv</option>
<option value="CATV RURAL">Catv Rural</option>
<option value="3ST HOTEL">3st Hotel</option>
<option value="4ST HOTEL">4st Hotel</option>
<option value="5ST HOTEL">5st Hotel</option>
<option value="DAS PHASE 1">Das Phase 1</option>
<option value="DAS PHASE 2">Das Phase 2</option>
<option value="DAS PHASE 3">Das Phase 3</option>
</select>
</body>
If you run the snippet, you'll see that making changes to the first will update the second select accordingly based on the defined map.
Hope this can help you out!

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'

How to use an input from a select option in html with javascript?

I want to assign a drop down option to a unique ID so that when it is selected, the javascript will take that ID and turn it into a variable which I can use to display the cost.
This is what I have so far:
<form>
<select>
<option name ="Bristol "value="40.0" id="BN1">Bristol - Newcastle</option>
</select>
<button type="button" onclick="BookingFare(); return false;">Submit</button><br>
</form>
function BookingFare() {
var price = 0;
//var ofAdults = document.getElementById('adults').value;
//var ofChildren = document.getElementById('children').value;
var BN1 = document.getElementById('BN1').value;
if (BN1) {
var price = price + 40;
}
document.getElementById('priceBox').innerHTML = price;
}
I can't get it to display the price, even when I just try to get it to print out "hello" when BN1 is selected it doesn't work. Can anyone tell me what I'm missing?
function BookingFare() {
var price = 0;
//var ofAdults = getElementById('adults').value;
//var ofChildren = getElementById('children').value;
var BN1 = document.getElementById('BN1').value;
if (BN1) {
var price = price + 40;
}
document.getElementById('priceBox').innerHTML = price;
}
<form>
<select id="BN1">
<option name ="Bristol "value="40.0" >Bristol - Newcastle</option>
</select>
<button type="button" onclick="BookingFare(); return false;">Submit</button><br>
</form>
<label id='priceBox'></label>

Categories