How to use selected option is variable select list - javascript

For my code i need 2 selects, the first select is static (4 options that dont change) and the second select is dependant on what is selected in the first select.
Then depending on what is chosen in de the second list a function is executed.
i found some example code one W3schools that allow me to make the whole list thing:
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_options3
So this works really well but now i dont know how to attach a function to the selected options in the second select since there is no where in the html to do something like an onchange.
Each option from the second select should have a function (in my code the selected option will display an image corresponding with the chosen option)
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>

Related

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>

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);
}

Get all select/option lists start by something

In an HTML page i have severals list.
<select name="salut-1358937506000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
<select name="salut-1358937582000-OK">
<option selected="" value="OK">OK</option>
<option value="OK">NOK</option>
</select>
...
In javascript, I want to get all select/option list which started by "salut-".
For theses list, i want to compare his name and his selected value.
I know it is possible in jQuery but can't use jquery, only javascript (JSNI with GWT exactly).
Have you an idea?
Thanks!
var selects = document.getElementsByTagName('select');
var sel;
var relevantSelects = [];
for(var z=0; z<selects.length; z++){
sel = selects[z];
if(sel.name.indexOf('salut-') === 0){
relevantSelects.push(sel);
}
}
console.log(relevantSelects);
You can use the getElementsByTagName function to get each SELECT name, for example:
var e = document.getElementsByTagName("select");
for (var i = 0; i < e.length; i++){
var name = e[i].getAttribute("name");
}
Then you can use the following code to get each OPTION for the SELECT, to do any necessary comparisons:
var options = e[i].getElementsByTagName("option")

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