Select prepended option by default - javascript

Okay I'm about to pull my hair out.
I'm hoping someone can help me.
I'm trying to prepend a "Select an Option" value to a dropdown menu and then make that the default selected option when the page loads.
For a brief background: I have been trying to combine Shopify's "Linked Options" and "Pick an Option" features. Sadly, when you try to implement both, the Linked Options feature overrides Pick an Option. (Pick an Option places a default "Select a ____" to the dropdown menu).
So I have taken a part of the Pick an Option and tried placing it in Linked Options.
Here is the code that I placed in that:
selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>').val('');
And here is the entire code:
<script>
// (c) Copyright 2016 Caroline Schnapp. All Rights Reserved. Contact: mllegeorgesand#gmail.com
// See https://docs.shopify.com/themes/customization/navigation/link-product- options-in-menus
var Shopify = Shopify || {};
Shopify.optionsMap = {};
Shopify.updateOptionsInSelector = function(selectorIndex) {
switch (selectorIndex) {
case 0:
var key = 'root';
var selector = jQuery('.single-option-selector:eq(0)');
break;
case 1:
var key = jQuery('.single-option-selector:eq(0)').val();
var selector = jQuery('.single-option-selector:eq(1)');
break;
case 2:
var key = jQuery('.single-option-selector:eq(0)').val();
key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
var selector = jQuery('.single-option-selector:eq(2)');
}
var initialValue = selector.val();
selector.empty();
var availableOptions = Shopify.optionsMap[key];
selector.prepend('<option value="">Select ' + {{ product.options[forloop.index0] | json }} + '</option>');
selector[0].selectedIndex = 0;
for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery('<option></option>').val(option).html(option).val('');
selector.append(newOption);
}
jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {
if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {
$(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');
}
else {
$(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');
}
});
if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
}
selector.trigger('change');
};
Shopify.linkOptionSelectors = function(product) {
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
if (variant.available) {
// Gathering values for the 1st drop-down.
Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];
Shopify.optionsMap['root'].push(variant.option1);
Shopify.optionsMap['root'] = Shopify.uniq(Shopify.optionsMap['root']);
// Gathering values for the 2nd drop-down.
if (product.options.length > 1) {
var key = variant.option1;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option2);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
// Gathering values for the 3rd drop-down.
if (product.options.length === 3) {
var key = variant.option1 + ' / ' + variant.option2;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option3);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
}
}
// Update options right away.
Shopify.updateOptionsInSelector(0);
if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
// When there is an update in the second dropdown.
jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
};
{% if product.available and product.options.size > 1 %}
var $addToCartForm = $('form[action="/cart/add"]');
if (window.MutationObserver && $addToCartForm.length) {
if (typeof observer === 'object' && typeof observer.disconnect === 'function') {
observer.disconnect();
}
var config = { childList: true, subtree: true };
var observer = new MutationObserver(function() {
Shopify.linkOptionSelectors({{ product | json }});
observer.disconnect();
});
observer.observe($addToCartForm[0], config);
}
{% endif %}

That looks like it'll take way too much time to grok. Snippet 1 demonstrates how to prepend an option to a select. Snippet 2 demonstrates how to use insertAdjacentHTML(). The attribute: selected which value can be: "selected" or true/false, purpose is to designate the default option. Details are commented in the code.
SNIPPET 1
// Reference the select
var sel = document.getElementById('sel');
// Create an option
var opt = document.createElement('option');
// Add a value
opt.value = '0';
// Add content
opt.textContent = '0';
// Make it default
opt.setAttribute('selected', true);
// Reference the first child of the select
var first = sel.firstChild;
// Insert box before the first
sel.insertBefore(opt, first);
<select id='sel' name='sel'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
SNIPPET 2
var sel = document.getElementById('sel');
sel.insertAdjacentHTML('afterbegin', '<option value="" selected=true>Select</option>');
// Reference the first child of select
var first = sel.firstChild;
// This commented out because I don't have the data to use it.
// first.textContent = "Select "+{{product.options[forloop.index0] || json}}+";
<script src='https://cdn.jsdelivr.net/handlebarsjs/4.0.5/handlebars.min.js'></script>
<select id='sel' name='sel'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
The first parameter of insertAdjacentHTML() is the location of insertion:
<section id='s1'>Content xxxxxxxxxxxxxxxxxxxxx</section>
▲-----------------▲----------------------------▲---------▲
beforebegin___afterbegin________________beforeend_afterend
The second parameter is the string that will be parsed into HTML. Basically inserAdjacentHTML() is innerHTML on steroids. Read about here.

Related

Object values only appending to one select option and stops on the next one [duplicate]

This question already has answers here:
Mulitple Elements with the same ID
(5 answers)
Closed 1 year ago.
I have data of this sort. I have arrays saved in an object, and am trying to append the options from my object into the select option. It is displaying correctly in the first select option, but not displaying on the second. The following is my code.
<script>
var stateObject = {
"Nairobi": {
"Delhi": ["new Delhi", "North\/Delhi"],
"Kerala": ["Thiruvananthapuram", "Palakkad"],
"Goa": ["North Goa", "South Goa"],
},
"Australia": {
"South Australia": ["Dunstan", "Mitchell"],
"Victoria": ["Altona", "Euroa"]
}, "Canada": {
"Alberta": ["Acadia", "Bighorn"],
"Columbia": ["Washington", ""]
},
}
window.onload = function () {
var countySel = document.getElementById("countySel"),
stateSel = document.getElementById("stateSel"),
districtSel = document.getElementById("districtSel");
for (var country in stateObject) {
countySel.options[countySel.options.length] = new Option(country, country);
}
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
countySel.onchange(); // reset in case page is reloaded
stateSel.onchange = function () {
districtSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[countySel.value][this.value];
for (var i = 0; i < district.length; i++) {
districtSel.options[districtSel.options.length] = new Option(district[i], district[i]);
}
}
}
</script>
When I append in select, it only applies in one select option, the other is not working. Any idea on how the second one can be affected.
//appending to this option
<select name="county" id="countySel" class="form-control" required>
<option value = "" selected="selected" class="form-control">--Select--</option>
</select>
//not appending to this option
<select name="county" id="countySel" class="form-control" required>
<option value = "" selected="selected" class="form-control">--Select--</option>
</select>
You cannot have 2 or more elements with the same I'd on the same page...
That is 2 countrySel IDs; so only 1 element will end up usable in js. Use different IDs...

Add new option to dropdown if none of the existing one match certain string exist using javascript

I have this drop down that I compare with an array. If a value in the array matches the text of one of the options in the dropdown, then it is selected:
JS -Step One:
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
Dropdown
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS - Step Two:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
}
}
}
}
Here comes my issue: The the code showed above works just fine, but I would like to be able to add a new option if an option with the same array value doesn't exist. In the example shown above, there are two values ('Apple' and 'Tomatoes") values in the array. When I iterate through the array and the dropdown, the 'Apple' option is selected, but, how can I then add a new 'Tomatoes' options, and then select it also? Thanks in advance, please let me know if more details are needed.
I would like to be able to add a new option if an option with the same array value doesn't exist..
you can clone an option node modify it and append it to parent node,
in the snippet I added a dedicated function;
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
outer:
for (var d = 0; d < array.length; d++) {
for (var i = 0; i < select[0].options.length; i += 1) {
if (select[0].options[i].text === array[d]) {
select[0].options[i].selected = true;
continue outer;
}
//if you haven't matched and are in last loop
if ( i === select[0].options.length - 1) {
addOpt(array[d], select[0].options[i])
}
}
}
}
function addOpt(x,clone){
var node = clone.cloneNode();
node.selected= true;
node.value= node.innerHTML= x;
clone.parentNode.appendChild(node)
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns ('topicSelect',topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option selected="" value=""></option>
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
One approach, using ES6 syntax is the following:
function populateExistingDropDowns(dd, array) {
// using 'let' rather than 'var' to declare variables,
// using document.querySelector(), rather than
// getElementsByClassName(), because d.qS has support
// in IE8 (whereas it does not support
// getElementsByClassName()); however here we get the
// first element that matches the selector:
let dropdown = document.querySelector('.' + dd),
// retrieving the collection of option elements,
// HTMLSelectElement.options, and converting that
// collection into an Array using Array.from():
options = Array.from(dropdown.options);
// iterating over each of the topics in the passed-in
// array, using Array.prototype.forEach():
array.forEach(function(topic) {
// filtering the array of <option> elements to keep
// only those whose text property is equal to the
// current topic (from the array):
let opts = options.filter(opt => topic === opt.text);
// if the opts Array has a truthy non-zero length:
if (opts.length) {
// we iterate over the returned filtered Array
// and, using Arrow function syntax, set each
// node's selected property to true:
opts.forEach(opt => opt.selected = true);
} else {
// otherwise, if the current topic returned no
// <option> elements, we find the <optgroup>
// holding the 'Crops' and append a new Child
// using Node.appendChild(), and the new Option()
// constructor to set the option-text, option-value
// default-selected property and selected property:
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
let dropdown = document.querySelector('.' + dd),
options = Array.from(dropdown.options);
array.forEach(function(topic) {
let opts = options.filter(opt => topic === opt.text);
if (opts.length) {
opts.forEach(opt => opt.selected = true);
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
To recompose the above, using ES5:
function populateExistingDropDowns(dd, array) {
// using 'var' to declare variables:
var dropdown = document.querySelector('.' + dd),
// using Array.prototype.slice(), with
// Function.prototype.call(), to convert the collection
// of <option> element-nodes into an Array:
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
// using the anonymous functions available to the
// Array methods, rather than Arrow functions,
// but doing exactly the same as the above:
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
function populateExistingDropDowns(dd, array) {
var dropdown = document.querySelector('.' + dd),
options = Array.prototype.slice.call(dropdown.options, 0);
array.forEach(function(topic) {
var opts = options.filter(function(opt) {
return topic === opt.text
});
if (opts.length) {
opts.forEach(function(opt) {
opt.selected = true;
});
} else {
dropdown.querySelector('optgroup[label=Crops]')
.appendChild(new Option(topic, topic, true, true));
}
});
}
var topicArray = ['Apples', 'Tomatoes'];
populateExistingDropDowns('topicSelect', topicArray);
<select class="topicSelect" multiple>
<optgroup label="Crops">
<option value="Apiculture">Apiculture</option>
<option value="Apples">Apples</option>
<option value="Aquaculture">Aquaculture</option>
<option value="Blueberries">Blueberries</option>
</optgroup>
<optgroup label="Add Option" class="youOwn">
<option value="own">Add Your Option</option>
</optgroup>
</select>
JS Fiddle demo.
References:
Array.from().
Array.prototype.filter().
Array.prototype.forEach().
Arrow functions.
document.querySelector().
HTMLOptionElement.
HTMLSelectElement.
let statement.
Node.appendChild().
Option() Constructor.
var statement.
Thank you all that responded to my question. I ended up using this instead:
function populateExistingDropDowns(dd, array) {
var select = document.getElementsByClassName(dd);
var opt = document.createElement('option');
for (var d = 0; d < array.length; d++) {
for (var q = 0; q < select[0].length; q++) {
if (select[0].options[q].text !== array[d]) {
opt.value = array[d];
opt.text = array[d];
select[0].children[1].appendChild(opt);
opt.selected = true;
} else {
select[0].options[q].selected = true;
}
}
}
}
Fiddle

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'

select multiselect option limit up to 2

I am using multiselect for different subject's I want to limit the select up to 2 and make the other's disabled in the same way if user deselect, Again the option must be available for the user.
<select multiple="multiple" class="subjects" name="subjects[]" style="float:left;width:205px;" size="5">
<option value='1'>subject1</option>
<option value='2'>subject2</option>
<option value='3'>subject3</option>
<option value='3'>subject3</option>
</select>
So far I have achieved to deselect only the last option which was selected after 2 and the code is as follow
/**
* Make sure the subject's limit is 2
*/
$(".subjects option").click(function(e){
if ($(this).parent().val().length > 2) {
$(this).removeAttr("selected");
}
});
Thank you.
Improved jQuery example, notice the (else enable) option, this fixes a bug on previous examples that disabled the select options permanently. Also removed the "Please select only two options." error message when possible.
http://jsfiddle.net/c9CkG/25/
jQuery(document).ready(function () {
jQuery("select").on("change", function(){
var msg = $("#msg");
var count = 0;
for (var i = 0; i < this.options.length; i++)
{
var option = this.options[i];
option.selected ? count++ : null;
if (count > 2)
{
option.selected = false;
option.disabled = true;
msg.html("Please select only two options.");
}else{
option.disabled = false;
msg.html("");
}
}
});
});
As an improvment on RobG's answer, you could unselect an option if it makes count > 2.
See: http://jsfiddle.net/c9CkG/3/ for a working example using jQuery.
function checkSelected(el) {
var msgEl = document.getElementById('msg');
var count = 0;
for (var i=0, iLen=el.options.length; i<iLen; i++)
el.options[i].selected? count++ : null;
// Deselect the option.
if (count > 2) {
el.options[i].selected = false;
el.options[i].disabled = true;
msgEl.innerHTML = 'Please select only two options';
}
}
Something like the following will do the job:
function checkSelected(el) {
var msgEl = document.getElementById('msg');
var count = 0;
for (var i=0, iLen=el.options.length; i<iLen; i++)
el.options[i].selected? count++ : null;
msgEl.innerHTML = count > 2? 'Please select only two options' : '';
}
</script>
<span>Please select a maximum of two options:</span>
<select multiple onchange="checkSelected(this);">
<option>0
<option>1
<option>2
<option>3
</select>
<br>
<span id="msg"></span>
I don't think it's a good idea to disable options, you only care that only two are selected when the form is submitted. Until then, it doesn't matter.
$(document).ready(function() {
var last_valid_selection = null;
$('#testbox').change(function(event) {
if ($(this).val().length > 5) {
alert('You can only choose 5!');
$(this).val(last_valid_selection);
} else {
last_valid_selection = $(this).val();
}
});
});

Categories