Fill multiselect dropdown depending on select - javascript

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/

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>

Dynamic Dropdown in Javascript with onchange

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?

Filling options values dynamically to dynamically added dropdown?

I am adding dropdowns dynamically by code it is rendered in browser like
<select id="contact-type1"></select>
<select id="contact-type2"></select>
...
Now I am trying the below code for dynamically selecting nth number of dropdown in order to fill option values in them.
function fillContactTypes()
{
var types = ["Phone","Whatapp","Facebook","Web","Fax"];
var select = document.getElementById('contact-type[*n]');
for(var i = 0; i < types.length; i++)
{
var option = document.createElement('option');
option.innerHTML = types[i];
option.value = types[i];
select.appendChild(option);
}
}
Please help me in the line "var select = document.getElementById('contact-type[*n]');
".
I have just added common class to all dropdowns and using jquery you can dynamically bind all dropdown as shown below.
var types = ["Phone","Whatapp","Facebook","Web","Fax"];
$(document).ready(function(){
fillContactTypes()
});
function fillContactTypes(){
var myselect = $('<select>');
$.each(types, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('.contact-type').append(myselect.html());
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="contact-type1" class="contact-type">
</select>
<select id="contact-type2" class="contact-type">
</select>
<select id="contact-type3" class="contact-type">
</select>
<select id="contact-type4" class="contact-type">
</select>

Set <select> element depending on another <select> element

I need a select element's options to change depending on the value of another.
<select id="first">
<option value="1">one</option> // When you click this one, all the values of #second change (arbitrary number of entries)
<option value="2">two</option> // When you click this one, all the values of #second change to something else (not necessarily the same number)
</select>
<select id="second">
<option value="thisChanges">soDoesThis</option>
<option value="thisToo">andThis</option>
</select>
<script>
$("#first").on("change", function() {
<pseudo>
if #first == "1"
#second = {"this", "that", "the other"}
else if #first == "2"
#second = {"more", "even more", "yet another", "still more"}
</pseudo>
}
</script>
This is pretty much what I'm after (took me years to figure out how to completely replace the values of a select box), but the button click event doesn't even work. It was working a minute ago, although the for loop was not.
Obviously for my use case I would check if the select is clicked and retrieve its value with .val(), but I figured this button is easier for debugging.
JSFiddle
HTML:
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button>
Click me
</button>
JS:
var list = ['11', 'Eleven', '12', 'Twelve', '13', 'Thirteen'];
$('button').on('click', function () {
alert('click');
var sel = $('#sel');
alert('1');
sel.empty();
alert('2');
for (i = 0, i < list.length; i+2) {
$('#sel').append('<option value="' + list[i] + '">' + list[i+1] + '</option>');
}
alert('3');
});
I think you requirement similiar to the cascading dropdownlist, if i have understood correctly.
Ex jquery code:
$(document).ready(function () {
$("#state").prop("disabled", true);
$("#country").change(function () {
if ($("#country").val() != "Please select") {
var options = {};
options.url = "/home/getstates";
options.type = "POST";
options.data = JSON.stringify({ country: $("#country").val() });
options.dataType = "json";
options.contentType = "application/json";
options.success = function (states) {
$("#state").empty();
for (var i = 0; i < states.length; i++) {
$("#state").append("<option>" + states[i] + "</option>");
}
$("#state").prop("disabled", false);
};
options.error = function () { alert("Error retrieving states!"); };
$.ajax(options);
}
else {
$("#state").empty();
$("#state").prop("disabled", true);
}
});
});
Kindly refer this good article for the complete code:
http://www.binaryintellect.net/articles/b58fde6b-415e-454d-985b-d5dc4ad2fca8.aspx
Hope it will helps
Thanks
Karthik
Since you specified jQuery, I'll give you a jQuery answer! Grab the value and the text from the selected option, and append a new one to the select:
$(document).on('change', '#two', function() {
var option_to_add = $(this).find("option:selected").text();
var number_of_options = $('#two option').length
$('#one').append($('<option>', {
value: number_of_options,
text: option_to_add
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="cash">Cash</option>
<option value="money">Money</option>
</select>
<select id="two">
<option value="stack">Stack</option>
<option value="overflow">Overflow</option>
<option value="my">My</option>
<option value="question">Question</option>
<option value="op1">Should be option 1: <a id="option1"></a></option>
</select> Should also be option 1:
<div id="option1"></div>
Based on your comments and changes to your post, if you just want to replace the options in a select element using a dummy array (or array of arrays,) you can do so the following way see code comments for details:
// dummy data array of arrays
var list = [
[11, "Eleven"],
[12, "Twelve"],
[13, "Thirteen"]
];
// click the button, replace the select contents
$('#btn').on('click', function() {
// build an array of option objects from an array of arrays
// see below
var opt_array = build_opt_array(list);
$('#sel').empty();
// add the new options
$(opt_array).each(function(index) {
$('#sel').append(opt_array[index]);
});
});
// helper function
// builds a new array of option html objects from
// an array of arrays
function build_opt_array(items) {
var opt_array = [];
$(items).each(function(index) {
var new_option = $('<option>', {
value: items[index][0],
text: items[index][1]
});
opt_array.push(new_option);
});
return opt_array;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<button id="btn">
Click me
</button>
To get the text found in the first Select field, use the .text() function after using find(":selected") on your desired select field.
$("#two").focus(function() {
document.getElementById("option1").innerHTML = $("#one").find(":selected").text();
});

How to change Selected Index when I only have the name?

I'm integrating Postcode anywhere with my web project. I'm using a drop drop for the county/state field. Postcode anywhere returns the name of the County. Can I change the Selected Index when I only have the name? (I'm using a number for the value field which relates to a database field).
I tried the following:
var f = document.getElementById("state_dropdown");
f.options.[f.selectedIndex].text = response[0].County;
I've tried to include the drop down code html here but I can't get it to work properly for some reason.
But of course this just changes the text field for the item in the drop down that is already selected.
I can query the database and find out what ID I have assigned the county but I'd rather not if there is another way.
Loop over the options until you have a match:
for (var i = 0; i < f.options.length; i++) {
if (f.options[i].text == response[0].Country) {
f.options.selectedIndex = i;
break;
}
}
Demo.
I would make a function and loop over the labels:
See: http://jsfiddle.net/Y3kYH/
<select id="country" name="countryselect" size="1">
<option value="1230">A</option>
<option value="1010">B</option>
<option value="1213">C</option>
<option value="1013">D</option>
</select>​
JavaScript
function selectElementByName(id, name) {
f = document.getElementById(id);
for(i=0;i<f.options.length;i++){
if(f.options[i].label == name){
f.options.selectedIndex = i;
break;
}
}
}
selectElementByName("country","B");
Just a variation on other answers:
<script type="text/javascript">
function setValue(el, value) {
var sel = el.form.sel0;
var i = sel.options.length;
while (i--) {
sel.options[i].selected = sel.options[i].text == value;
}
}
</script>
<form>
<select name="sel0">
<option value="0" selected>China
<option value="1">Russia
</select>
<button type="button" onclick="setValue(this, 'Russia');">Set to Russia</button>
<input type="reset">
</form>

Categories

Resources