Dynamic Dropdown in Javascript with onchange - javascript

I am pretty new to JavaScript. I am trying to create dropdowns that are dynamic in the sense that when you select a value in the first dropdown the second dropdown automatically updates for all possible values for the value selected and vice versa.
I am able to do it one way but not the other way around. Please find attached the screenshot of my code here. I would be grateful for any answers. Thanks.
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
if (s1.value!=""){
if (s1.value!=""){
s2.innerHTML=""
} else {
s1.innerHTML=""
}
if(s1.value == "Chevy"){
var optionArray = ["|","Camaro|Camaro","Corvette|Corvette","Impala|Impala"];
} else if(s1.value == "Dodge"){
var optionArray = ["|","Avenger|Avenger","Challenger|Challenger","Charger|Charger"];
} else if(s1.value == "Ford"){
var optionArray = ["|","Mustang|Mustang","Shelby|Shelby"];
}
for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
if(s2.value == "Camaro" || s2.value=="Corvette"|| s2.value=="Impala"){
var optionArray1 = ["|","Chevy|Chevy"];
} else if(s2.value == "Avenger" || s2.value=="Challenger"|| s2.value=="ImpChargerala"){
var optionArray1 = ["|","Dodge|Dodge"];
} else if(s2.value == "Mustang" || s2.value=="MuShelby"){
var optionArray1 = ["|","Dodge|Dodge"];
}
for(var option in optionArray1){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s1.options.add(newOption);
}
}
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id,'slct2')">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2">
<option value=""></option>
<option value="Camaro">Camaro</option>
<option value="Corvette">Dodge</option>
<option value="Impala">Impala</option>
<option value="Avenger">Avenger</option>
<option value="Corvette">Dodge</option>
<option value="Challenger">Challenger</option>
<option value="Charger">Charger</option>
<option value="Mustang">Mustang</option>
<option value="Shelby">Shelby</option>
</select>
<hr />

Hopefully this should explain a lot. See the comments for why certain parts work the way they do.
This code could be shorter, but I wanted to make it more clear. (For more info about almost any JS feature, MDN is a good source. You can google the feature's name and MDN (like "Arrays MDN") to find results on that site.)
const
// Identifies HTML elements in the DOM that we will need
makesDropdown = document.getElementById("makesDropdown"),
modelsDropdown = document.getElementById("modelsDropdown"),
// Puts Makes and Models in a `cars` object for reference
cars = {
Chevy: ["Camaro", "Corvette", "Impala"],
Dodge: ["Avenger", "Challenger", "Charger"],
Ford: ["Mustang", "Shelby"]
}
;
// Calls the appropriate function when a selection changes
makesDropdown.addEventListener("change", updateModelsDropdown);
modelsDropdown.addEventListener("change", updateMakesDropdown);
// Defines listener functions
function updateModelsDropdown(event){
let
// The "target" of the `change` event is the input that changed
thisMake = event.target.value,
// Gets the array of models from `cars` (If no make is selected, uses all models)
relevantModels = cars[thisMake] || getAllModels();
modelsDropdown.selectedIndex = 0; // Shows the first (blank) option
// The select element's children are the options
let optionElements = modelsDropdown.children;
for(let option of optionElements){
// Uses CSS to hide (or unhide) HTML elements
option.classList.add("hidden");
// Keeps the blank option as well as the ones included in the array
if(relevantModels.includes(option.value) || option.value === ""){
option.classList.remove("hidden");
}
}
}
function updateMakesDropdown(event){
let
thisModel = event.target.value,
relevantMake = "",
// Gets an array of the "keys" for an object
allMakes = Object.keys(cars);
// Loops through the keys and tests each corresponding value (ie, each array of models)
for(let make of allMakes){
let models = cars[make];
// Finds the key whose value includes the selected model
if(models.includes(thisModel)){
// Saves the name of the key so we can select it in the makesDropdown
relevantMake = make;
}
}
let optionElements = makesDropdown.children;
for(let i = 0; i < optionElements.length; i++){
// Finds the index of the matching value
if(relevantMake === optionElements[i].value){
// Selects the option by its index
makesDropdown.selectedIndex = i;
}
}
}
// Defines a helper function
function getAllModels(){
// Gets an array of the "keys" for an object
const makes = Object.keys(cars);
const models = []; // Starts with an empty array to push models into
for(let make of makes){
// `cars[make]` retrieves the value (array of models) for that key
// `...` spreads the array into individual values (models)
// `push` adds each model to the new `models` array
models.push(...cars[make]);
}
return models;
}
.hidden{ display: none; }
<hr />
<h2>Choose Your Car</h2>
<hr /> Choose Car Make:
<select id="makesDropdown">
<option value=""></option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr /> Choose Car Model:
<select id="modelsDropdown">
<option value=""></option>
<option value="Camaro">Camaro</option>
<option value="Corvette">Corvette</option>
<option value="Impala">Impala</option>
<option value="Avenger">Avenger</option>
<option value="Challenger">Challenger</option>
<option value="Charger">Charger</option>
<option value="Mustang">Mustang</option>
<option value="Shelby">Shelby</option>
</select>
Note:
Selecting the blank option in the "makesDropdown" automatically resets the "modelsDropdown" so all models are available for the next selection, as one might expect. However, selecting the blank option in the modelsDropdown has no such effect. How would you add this feature to improve user experience?

Related

JS select option based on previous option

I have a form and I wish that second select option depends on first. It means if I select DEV_1_OLD otption it wont be showed in the second select list. How to do it with JS?
I started something like that but it doesnt work as I expected
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
console.log(op.length);
var opClone = op;
for (var i = 0; i < op.length; i++) {
opClone[i] = document.createElement('option');
// opClone[i].textContent = op[i].value;
// opClone[i].value = op[i].value;
document.getElementById('s12').appendChild(opClone[i]);
}
}
</script>
you need to add a condition to check if the option you appending is the selected one
<select id="s11" name="source" onchange="preapreSelectOptions()">
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
</select>
Target Environment:
<select id="s12" name="target" required>
</select>
<script>
function preapreSelectOptions () {
var op = document.getElementById("s11").getElementsByTagName("option");
var selected = document.getElementById("s11")
for (var i = 0; i < op.length; i++) {
// check if option is not selected
if(op[i].value != selected.options[selected.selectedIndex].value) {
o = document.createElement('option')
o.value = op[i].value
o.text = op[i].text
document.getElementById('s12').appendChild(o);
}
}
}
</script>
A little improvement for your code so you can dynamically generate the next option list:
Add conditional checking if value not selected
Make the function preapreSelectOptions accept argument so you can automatically generate new list for next select element based on current selection.
When call the preapreSelectOptions function, pass the current element id and next element id.
//Make it accept argument so you can automatically generate new list for next select
function preapreSelectOptions(currentSelectedElement, nextSelectElementId){
let selectedValue = document.getElementById(currentSelectedElement).value
//list the remain value in case you need it for other logic
let remainValue = function(){
let selectOptionList = document.getElementById(currentSelectedElement).children
let arr = []
for(var i = 0; i < selectOptionList.length; i++){
if(selectOptionList[i]["value"] !== selectedValue){
arr.push(selectOptionList[i]["value"])
}
}
return arr
}()
//generate option
for(var i = 0; i < remainValue.length; i++){
let newOption = document.createElement("option")
newOption.value = remainValue[i]
newOption.textContent = remainValue[i]
document.getElementById(nextSelectElementId).appendChild(newOption)
}
}
s11<br>
<select id="s11" name="source" onchange="preapreSelectOptions('s11','s12')" value="">
<option value=""></option>
<option value="DEV_1_OLD">DEV_1_OLD</option>
<option value="TEST_OLD">TEST_OLD</option>
<option value="PROD_OLD">PROD_OLD</option>
<option value="PROD_NEW">PROD_NEW</option>
<option value="PROD_LATEST">PROD_LATEST</option>
</select>
<br>
s12<br>
<select id="s12" name="source" onchange="preapreSelectOptions('s12','s13')">
</select>
<br>
s13<br>
<select id="s13" name="source">
</select>

two html select conflict

I have two html select element that the second one is disabled at first and only become enable if user choose one option from first select. consider we have 2 options in first select -> a , b if user choose a : in the second select options should be : a1,a2 if user choose b : in the second select options should be : b1,b2 ... I dont know what am i doing wrong that these two select options have conflict with each other !!!
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
All you need to do is clear out the previous entries in the second drop down every time a selection is made in the first one.
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option value="a"> a </option>
<option value="b"> b </option>
</select>
<select id="sub-category" required disabled> </select>
<!-- empty select -->
<script>
document.getElementById("main-category").onchange = function() {
// Clear out the second list before adding new items to it
document.getElementById('sub-category').innerHTML = "";
// *******************************************************
document.getElementById('sub-category').disabled = false;
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "a1";
opt0.innerHTML = "a1";
opt1.value = "a2";
opt1.innerHTML = "a2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
} else if (this.value == 'b') {
//first remove all previous options then add new ones
if (document.getElementById('sub-category').getElementsByTagName('option')[0]) { //check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[0];
document.getElementById('sub-category').removeChild(opt);
}
if (document.getElementById('sub-category').getElementsByTagName('option')[1]) {//check if there is a option then remove it
var opt = document.getElementById('sub-category').getElementsByTagName('option')[1];
document.getElementById('sub-category').removeChild(opt);
}
opt0.value = "b1";
opt0.innerHTML = "b1";
opt1.value = "b2";
opt1.innerHTML = "b2";
document.getElementById('sub-category').appendChild(opt0);
document.getElementById('sub-category').appendChild(opt1);
}
};
</script>
But, beyond that, your code needs to be cleaned up quite a bit because you shouldn't be scanning the document for the element you want to work with over and over again when you've already found it before. That's extremely wasteful.
Also, .innerHTML is for passing strings that contain HTML so that the HTML parser can parse the string and update the DOM accordingly. You are just setting plain strings with no HTML in them, so you should be using .textContent instead, which doesn't invoke the HTML parser and is more efficient.
Next (just FYI), if you want the value of an option to be the same as the text that is displayed to the user, you don't need to set a value for that option. The value is the contents of the option element by default.
Really, the entire operation can be made so much simpler by simply making new options in list2 based on the first letter of the option chosen in list1.
// Get references to the elements you'll be working with just once:
var list1 = document.getElementById("main-category");
var list2 = document.getElementById('sub-category');
list1.onchange = function() {
list2.disabled = false;
var newHTML = ""; // A string that will contain the new HTML for the second list
// Loop the amount of times we find <option> elements in list one, but start
// at the second one to account for the first one, which isn't really a true choice
for(var i = 1; i < list1.querySelectorAll("option").length; i++){
// Build up a string that the new option should be made from using the
// first character from the option found in list 1
newHTML += '<option>' + list1.value.substr(0,1) + i + '</option>';
}
// By setting a new value for .innerHTML, the old values get thrown out.
list2.innerHTML = newHTML;
};
<select id="main-category" required>
<option disabled selected> choose one option </option>
<option>a</option>
<option>b</option>
</select>
<select id="sub-category" required disabled> </select>

Javascript get specific values from array list

<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
I have the above List on my HTML select field.
I want to be able to get only the values --Product--, --Software--, --Services--
So I created an loop to go throw the list of products and used the method startwith to pickup the values starting with "--".
function loadFilter() {
var x = document.getElementById('List');
var i;
var n;
for (i = 0; i < x.length; i++) {
str = x[i].text
var n = str.startsWith('--');
flag = true;
if (n == true) {
alert(x[i].text); // list --Product--, --Software--, --Services--
alert(x[3].text); // prints from the LIST <product1> and not <--Services-->
}
}
}
So when the flag is true, the alert(x[i].text); list correctly the values (--Product--, --Software--, --Services--).
But when I try to get them by their values(index), E.G ..I need to get only (--Services--), so I use x[3].text), but this returns me the whole List values >> and not <--Services-->.
You can use the below code to populate array arr with the list of options having "--".
Then you can use arr[2] to get --Services--.
var arr = [];
[].slice.call(document.querySelectorAll("#List option")).map(function(el){
if (el.text.indexOf("--") === 0) arr.push(el.text);
});
console.log(arr)
console.log(arr[2])
<select name="List" id="List">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
Here you go:
function loadFilter() {
var element = document.getElementById('List');
var children = element.children;
var filtered = [];
for (var i = 0; i < children.length; i++) {
if (children[i].textContent.startsWith('--')) {
filtered.push(children[i].textContent);
}
}
return filtered;
}
To recap what the function did:
Get the element "List"
Get the children of "List"
Create an array to hold elements that pass the filter
Go through each element and add those with match the specified regex
Return the elements that pass the filter
I'm still not entirely sure what you're trying to do. --Services-- is index 9, not 3. To get --Services-- you need x[9].text
If you want to rearrange the three --xx-- into their own index, you need to push them into a new array, like so:
var output = []
if (n === true) output.push(x[i].text)
console.log(output[2]) // --Services--
You can use simple forEach loop to loop through elements like here, but first you need to create Array from your DOM Node list:
var list = Array.from(x);
list.forEach((value,index)=>{
if (value.text.startsWith('--')){
alert(value.text);
}
});
I've put it up on fiddle so you can check:
https://jsfiddle.net/pegla/qokwarcy/
First of all, you don't seen to be using your flag at all.
If I understood it correctly, you are trying to get --Services-- using x[3].text, but if you count your whole list the element at index [3] is the . You can verify that with the code bellow:
f (n == true) {
alert('index '+ i + ': ' + x[i].text); // list --Product--, --Software--, --Services--
}
You could create a new array containing the filtered options and then access the with the known index:
var filteredArray = [];
f (n == true) {
filteredArray.push(x[i]); //insert the element in the new array.
}
alert(filteredArray[2].text) //print --Service--, the third element of filtered array.
Remember that javascript has zero indexed array, so the first element has index 0, so, in order to acces the third element you'll need the index 2.
May be you want to try using optgroups?
Something like this:
<select name="List" id="List">
<option value="">-Select-</option>
<optgroup label="--Product--">
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
</optgroup>
<optgroup label="--Software--">
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
</optgroup>
<optgroup label="--Services--">
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</optgroup>
</select>
Then,
var select = document.getElementById('List');
var optgroups = select.getElementsByTagName('optgroup');
console.log(optgroups[2].label);
Will show:
--Services--
try:
function load() {
list = document.getElementById('List');
var data = document.getElementsByTagName('option');
currentCatagory=null;//the current selected catagory
currentvalue=null;
listdata=[];
//for all the options
for(cnt = 0; cnt < data.length; cnt++){
var e = data[cnt].innerHTML;//get option text
if(e.startsWith('-')){//test to make a catagory out of it
if(currentCatagory!=null)//do not concat is listdata is null
listdata=listdata.concat(currentCatagory);
currentCatagory = {"this":e,"listOfItems":[]};//create the catagory
}else if(currentCatagory!=null){//make sure currentCatagory is not null
var l=currentCatagory.listOfItems;//get the Catagory's list
currentCatagory.listOfItems = l.concat(e);//and add e
}
}
listdata=listdata.concat(currentCatagory);//add last catagory
//sets the list to show only catagories
var inner='';
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
list.innerHTML=inner;
}
function update(){
//check to make sure everything is loaded
if(typeof list=='undefined'){
load();
}
var inner='';//the new options
var value=list.options[list.selectedIndex].innerHTML;
if(value==currentvalue) return;
if(value.startsWith('-')){//if catagory
if(value.startsWith('--')){//if not -Select-
for (i = 0; i < listdata.length; i++) {//for all catagories
if(value==listdata[i].this){//if it is the current selected catagory then...
currentCatagory=listdata[i];//update the currentCatagory object
inner+=parseOp(listdata[i].this);//parse as option and append
//then append catagory's items
for(item in listdata[i].listOfItems){
inner+=parseOp(listdata[i].listOfItems[item]);
}
}else{//appends the other catagories
inner+=parseOp(listdata[i].this);
}
}
}else{//if it is '-select-' then just append the catagories
for (i = 0; i < listdata.length; i++) {
inner+=parseOp(listdata[i].this);
}
}
//set the new options
list.innerHTML=inner;
}
}
function parseOp(str){
//parse the options
return '<option value="">'+str+'</option>';
}
<select name="List" id="List" onchange="update();">
<option value="">-Select-</option>
<option value="">--Product--</option>
<option value="">product1</option>
<option value="">product2</option>
<option value="">product3</option>
<option value="">--Software--</option>
<option value="">software1</option>
<option value="">software2</option>
<option value="">software3</option>
<option value="">--Services--</option>
<option value="">service1</option>
<option value="">service2</option>
<option value="">service3</option>
</select>
and to set the dropdown box you will have to run load() otherwise load() will only be called after the first change event occurs.

Fill multiselect dropdown depending on select

I have a select dropdown list and a multiselect dropdown. And i want the multiselect one to be depended on the select one. How can i do it?
<div class="row">
<div class="col" ><label>Which class: </label><select name="type_of_subject_c" id="type_of_subject_c" tabindex="1">
<option value="" selected="selected">--не выбрано--</option>
<option value="5">5th </option>
<option value="6">6th</option>
<option value="7">7th</option>
<option value="8">8th</option>
</select>
</div>
And i want, for example, if a person chose 5th - show in the multiselect field such options as "Math", "English", "Literature"
If a person chose 6th - show "Math", "Science", "Music"
etc.
<div class="row">
<div class="col"><label>Coruses: </label><select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1" >
<option value="math">Math</option>
<option value="eng>English</option>
<option value="lit">Literature</option>
First of all you should always add code to your question even if it is not working. Stackoverflow is a place to learn, how can we help you if you don't share your work.
Array data contains all your data. We add options to both selects dynamically.
Function init() is where it starts. To change the data we need to add an event listener to our second select like so
select1.addEventListener('change', function(e) ...
Here is working example. Please read my comments to have better understanding. If you have any questions don't hesitate to ask.
var data = [
{ subject : 'one',
selected: true,
courses: ['Math_one', 'English_one', 'Literature_one']
},
{ subject : 'two',
courses: ['Math_two', 'English_two', 'Literature_two']
},
{ subject : 'three',
courses: ['Math_three', 'English_three', 'Literature_three']
},
{ subject : 'four',
courses: ['Math_four', 'English_four', 'Literature_four']
},
{ subject : 'five',
courses: ['Math_five', 'English_five', 'Literature_five']
},
{ subject : 'six',
courses: ['Math_six', 'English_five', 'Literature_six']
}
];
var select1 = document.getElementById('type_of_subject_c');
var select2 = document.getElementById('course_subj_c');
var resultText = document.getElementById('currentlySelected');
// Your result, do whatever you want
var selectedOptions = [];
function init(data) {
var subjects = [];
for (var i = 0; i < data.length; i++) {
var element = data[i];
// Add subjects to subjects array
subjects.push(element.subject);
// We skip if current element is not selected
if (!element.selected) {
continue;
}
// If element is selected we change content of `select2`
if (element.selected) {
fillSelectOptions(select2, element.courses);
}
}
// Append all subjects as select options to `select1`
fillSelectOptions(select1, subjects);
}
// Lets add event listener `onChange` to `select`
select1.addEventListener('change', function(e) {
// Based on selected/current value we will change data options of `select2`
var selectedValue = e.target.value;
// Clear result text each time we change `select1`
resultText.innerHTML = '';
selectedOptions = [];
// Before we append new data lets clear old one
clearSelect2Options();
// Lets find related data to selected/current value
for (var i = 0; i < data.length; i++) {
var element = data[i];
if (element.subject === selectedValue) {
fillSelectOptions(select2, element.courses);
break;
}
}
});
select2.addEventListener('change', function(e) {
var options = document.querySelectorAll('#course_subj_c option');
resultText.innerHTML = '';
selectedOptions = [];
for (var i = 0; i < options.length; i++) {
var option = options[i];
if (option.selected) {
selectedOptions.push(option.value);
}
}
// Our Result is :
//console.log(selectedOptions);
// Append result to `resultText` convert array to string via `join()`
resultText.innerHTML = selectedOptions.join();
});
function fillSelectOptions(selector, dataOptions) {
for(var i = 0; i < dataOptions.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = dataOptions[i];
opt.value = dataOptions[i];
selector.appendChild(opt);
}
}
function clearSelect2Options() {
var i;
for(i = select2.options.length - 1 ; i >= 0 ; i--) {
select2.remove(i);
}
}
init(data);
favorite
<select id="type_of_subject_c" name="type_of_subject_c">
</select>
<select name="course_subj_c[]" id="course_subj_c" multiple="multiple" tabindex="1">
</select>
<div>Currently selected <span id="currentlySelected"></span></div>
You can't achieve this just using HTML.
You need to use JavaScript in order to populate the other dropdown with elements depending on the value chose in the first dropdown.
Add an onchange event to the first dropdown.
Inside this function, clear all the option elements of the second dropdown. Then depending on the selected value of the first dropdown, fill the second one. Here an example of code using jQuery.
<select name="first-dropdown" id="first-dropdown" onchange="processValue();">
<option value="" selected="selected">Default Option</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="second-dropdown" multiple="multiple" id="second-dropdown">
<option value="" selected="selected">Select option in the first dropdown</option>
</select>
<script type="text/javascript">
function processValue() {
var firstChoice = $('#first-dropdown').val();
// ensure you didn't select the default option
if (firstChoice !== "") {
$('#second-dropdown').empty();
switch (firstChoice) {
case "1":
$('#second-dropdown').append('<option value="first1">First 1</option>');
$('#second-dropdown').append('<option value="first2">First 2</option>');
break;
case "2":
$('#second-dropdown').append('<option value="second1">Second 1</option>');
$('#second-dropdown').append('<option value="second2">Second 2</option>');
break;
// ... other cases
default:
break;
}
// init jquery checkbox plugin again
$('#second-dropdown').multipleSelect();
}
}
</script>
Here the link to jsfiddle:
https://jsfiddle.net/37swkpso/

delete duplicate element in selected option

I have Two selected option: the first is contact and the second is contact2. the element in the first select option will be added to the second list.
the function bellow let me to add all element without problems, but I want to add just the element with unique id, because the first list contain many duplicate option id.
function addAllElement(object){
contacts = document.getElementById('contact');
long = object.options.length;
for (i=0;i<long;i++){
txt = object.options[i].text;
valor = object.options[i].value;
idd=object.options[i].id;
addOption(contact2,i,idd,txt,valor);
}
}
this is an example of the list with duplicate id
<select name="contacts" id="contacts" multiple="">
<option value="7147582,2" id="77">Test</option>
<option value="7189466,2" id="62">test2</option>
<option value="7" id="62">contact3</option>
<option value="72" id="64">ERRZERZE, zerzerze</option>
<option value="71" id="62">contact 5</option>
<option value="72y" id="001">contact 6</option>
</select>
As you see many element with the same id, and the predicted result is a list without duplicate element
I would create an array that stores each id per iteration. If the id has already been created, then do not add that to the second select. Redo your function in this manner:
function addAllElement(object) {
var i, valor, idd, txt;
var long = object.options.length;
var ids = [];
for (i = 0; i < long; i++) {
txt = object.options[i].text;
valor = object.options[i].value;
idd = object.options[i].id;
if (ids.indexOf(idd) == -1) {
addOption("contact2", i, idd, txt, valor);
ids.push(idd);
}
}
}
You can check for the length of element with that id before calling addOption method:
for (i=0;i<long;i++){
txt = object.options[i].text;
valor = object.options[i].value;
idd=object.options[i].id;
if(document.getElementById(idd).length)
addOption(contact2,i,idd,txt,valor);
}

Categories

Resources