Dynamically removing options from select box - javascript

I want to dynamically remove options from a select box..
<select name="goal1">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
<select name="goal2">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
<select name="goal3">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
There are, as you can see, three of these select boxes on the page with the exact same options, is there any way to dynamically remove options of the other select boxes based on selections made from the others.
So for example, if in the first of three select boxes, I choose 'Fat Loss', is there any way to remove that option from the other 2 select boxes to avoid duplication in the input?
Then if an option gets unselected, the option needs to reappear in the other select boxes..

Yes there is. Check this JSFiddle. When selecting an item in one of the three dropdown boxes, the options are removed from the other two.
$(document).ready(function () {
$("select").on("change", function () {
// Show all options
$("option").show();
// Get an array of all current selections
var selected = [];
$("select").each(function () {
selected.push($(this).val());
});
// Remove all selected options, except the current showing one, from all lists
$("select").each(function () {
for (var i = 0; i < selected.length; i++) {
if (selected[i] != $(this).val()) {
$(this).find("option[value='" + selected[i] + "']").hide();
}
}
});
});
});
Edit: I've updated the fiddle with a new version which lets options reappear when they get unselected in other lists. Not sure if it's the best way of doing this though...

Related

Get selected optgroup in JavaScript

I have the below select tag with two optgroup.
<select id="linkSelector" class="form-control" onchange="linkDropDown();">
<optgroup label="Input">
<option value="default">Road type</option>
<option value="lanes">Lanes</option>
<option value="length">Length</option>
<option value="speed">Speed</option>
</optgroup>
<optgroup label="Ouput">
<option value="congestion">Congestion</option>
<option value="speed_output">Speed</option>
<option value="travel_time">Travel Time</option>
</optgroup>
</select>
I would like to execute myFuncton() depending on the selected optgroup.
For example if one of the dropdown value belong to <optgroup label="Input">, then execute myFunction().
I tried this:
var linkSelector = document.getElementById('linkSelector')
opt = linkSelector.getElementsByTagName('optgroup')
if (opt[0].label =='Input'){
myFunction()
}
One way to go about this, would be to get the selected option for the select field, then find out it's parent's label.
var label = document.getElementById('linkSelector').selectedOptions[0].parentElement.label;
if (label === "Input") {
myFunction();
}

How to show/hide items from a select list based on another selection

In JavaScript, how to show/hide items from a select list based on another selected option that contain a certain word or words?
I am very new to JavaScript, so any help would be appreciated.
There are two drop-downs: "group" and "alph".
<select name="group">
<option value="Angry (Two)">Angry (Two)</option>
<option value="Happy (Two)">Happy (Two)</option>
<option value="Sad">Sad</option>
<option value="Tired (One)">Tired (One)</option>
</select>
<select name="alph">
<option value="ABC">ABC</option>
<option value="ABC-1">ABC-1</option>
<option value="ABC-2">ABC-2</option>
<option value="DEF">DEF</option>
<option value="DEF-1">DEF-1</option>
<option value="DEF-2">DEF-2</option>
<option value="DEF-3">DEF-3</option>
</select>
Without IDs, for the first dropdown (name group), if the selected value contains " (Two)", then the list will only show:
<select name="alph">
<option value="ABC-2">ABC-2</option>
<option value="DEF-2">DEF-2</option>
</select>
If the user changes selection, and the selected value contains " (One)", then the list will only show:
<select name="alph">
<option value="ABC-1">ABC-1</option>
<option value="DEF-1">DEF-1</option>
</select>
If the user changes selection, and the selected value does not contain neither " (One)" or " (Two)", then the list will show:
<select name="alph">
<option value="ABC">ABC</option>
<option value="DEF">DEF</option>
<option value="DEF-3">DEF-3</option>
</select>
Note: I am not able to add IDs or attributes. I can only access the name of the select and the value.
Use data-* to create groups, then use a querySelector to get all the options and test if they are apart of the group or not. If they are apart of the group show them otherwise hide them.
// The main group
let groups = document.querySelector('select[name=group]')
// Add a change event
groups.addEventListener('change', (e) => {
// Get the currently selected Group
let current = e.target.options[e.target.selectedIndex]
// Get the data-group number
let group = current.getAttribute('data-group')
// Get all the items from the second dropdown
let opts = Array.from(document.querySelectorAll('select[name=alph]>option'))
// Hide items that are not appart of the group
opts.forEach(itm => itm.style.display = itm.getAttribute('data-group') == group || !itm.getAttribute('data-group') ? 'initial' : 'none')
// Reset the the selection
document.querySelector('select[name=alph]').selectedIndex = 0
})
/* Hide option two items by default */
select[name=alph]>option[data-group]{display:none;}
<select name="group">
<option>Select One...</option>
<option data-group="1" value="Angry (Two)">Angry (Two)</option>
<option data-group="2" value="Happy (Two)">Happy (Two)</option>
<option data-group="3" value="Sad">Sad</option>
<option data-group="4" value="Tired (One)">Tired (One)</option>
</select>
<select name="alph">
<option>Select One...</option>
<option data-group="1" value="ABC">ABC</option>
<option data-group="1" value="ABC-1">ABC-1</option>
<option data-group="2" value="ABC-2">ABC-2</option>
<option data-group="2" value="DEF">DEF</option>
<option data-group="3" value="DEF-1">DEF-1</option>
<option data-group="3" value="DEF-2">DEF-2</option>
<option data-group="4" value="DEF-3">DEF-3</option>
</select>

How to make one select being depending to another select?

I have two selects2: #one and #two.
one:
<select id="one">
<option value="127">Currency</option>
<option value="133">Banks</option>
<option value="134">Credits</option>
<option value="142">Pokemons</option>
</select>
two:
<select id="two">
<optgroup label="Currency">
<option value="127">KZT</option>
<option value="133">USD</option>
<option value="134">EUR</option>
<option value="142">RUB</option>
</optgroup>
<optgroup label="Games">
<option value="11">CS:GO</option>
<option value="2233">BDSM</option>
<option value="33">Work</option>
<option value="222">WOW</option>
</optgroup>
</select>
#
When I change selected item in #one I'd like to set all option groups in #two, which is not equal to #one:selected - to 'hidden'.
It works on simple selects, but because I use a select2 plugin I face a problem (items don't hide, because select2 generates his own items on change the .select).
#
This is my code:
$(".select2").on('change', function () {
var target = $("#two");
var currentSelected = $(this).find(':selected').text();
var targetOptGroups = target.find('optgroup');
$.each(targetOptGroups, function (i, value) {
if(value.label != currentSelected){
$(value).addClass('hidden');
}
else{
$(value).removeClass('hidden');
}
});
});
I want to see only 'Currency' optgroup in #two when I select 'Currency' in #one.

Jquery function to split option list into hierarchical select

I have list that looks like this:
<select>
<option value="All" selected="selected">- Any -</option>
<option value="16">Africa</option>
<option value="17">Asia</option>
<option value="56">-China</option>
<option value="57">-Japan</option>
<option value="19">Canada</option>
<option value="20">-Alberta</option>
<option value="21">-British Columbia</option>
<option value="22">-Manitoba</option>
<option value="23">-New Brunswick</option>
<option value="24">-Newfoundland & Labrador</option>
<option value="25">-Northwest Territories</option>
<option value="26">-Nova Scotia</option>
<option value="27">-Nunavut</option>
<option value="28">-Ontario</option>
<option value="29">-Prince Edward Island</option>
<option value="30">-Quebec</option>
<option value="31">-Saskatchewan</option>
<option value="32">-Yukon</option>
<option value="33">Central & South America</option>
<option value="34">Europe</option>
<option value="35">Republic of Ireland</option>
<option value="36">United Arab Emirates</option>
<option value="37">United Kingdom</option>
<option value="38">-England</option>
<option value="39">-Northern Ireland</option>
<option value="40">-Scotland</option>
<option value="41">-Wales</option>
</select>
I can't change the HTML, but need to split the select into two selects by jQuery first the show the top level choices then for example if Canada was chosen show a second drop down with the provinces. This has to be dynamic as the underlying list might change with the time.
I understand that it would be much easier if there would be optgroups but unfortunately this is out of my control. So basicly i need to convert this simple list into hierarchical select in the browser.
You can use below query to split continents and countries select box.
NOTE - put id="select" for main select box.
$(function(){
var continent='';
$('#select option:gt(0)').each(function(){
var value = $(this).val();
//check if option text don't have '-' in it, then take it as
// continent and create a select box with same id
if($(this).text().indexOf("-")==-1 && continent!=value)
{
continent=value;
$('#select').after('<select id="'+continent+'" style="display:none" class="country"></select>');
}
else
{
//add option to the newly created select box
$('#'+continent).append($(this));
}
});
//remove all country select box which are empty
$('.country').filter(function(){
return $(this).children().length ==0;
}).remove();
//bind change event to select box to show / hide country select box
$('#select').change(function(){
$('.country').hide();
$('#'+$(this).val()).show();
});
});
DEMO

how to select a particular drop down option element

I want to use this function to work on all my drop down lists. Problem: the first drop down works okay, but hen I try select any option in the 2nd drop down selections. It places the value from the first group in the span of the second group. I want the span to have the value from its own group. I would like to use this on multiple groups.
<script>function displayResult(xspan,xselect)
{
var x=document.getElementById(xselect).selectedIndex;
alert(x);
var newTxt = document.getElementsByTagName("option")[x].value;
document.getElementById(xspan).innerHTML = newTxt;
//alert(document.getElementsByTagName("option").length);
}
</script>
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
<option value="">Phone Numbers</option>
<optgroup label="Shipping">
<option value=" - 800-463-3339">FedEx</option>
<option value=""></option>
</optgroup>
</select>
<span id="ShowPhone"></span>
<select id="myParts" onchange="displayResult('ShowParts','myParts')">
<option value="">Qik Parts list</option>
<optgroup label="BATT">
<option value="1">1</option>
<option value="2">1</option>
<option value="2">1</option>
<option value="2"><1/option>
</optgroup>
</select>
<span id="ShowParts"></span>
Chage the id and the displayResult of the second dropdown:
First dropdown:
<select id="myPhones" onchange="displayResult('ShowPhone','myPhones')">
Second dropdown:
<select id="NewNameID" onchange="displayResult('ShowPhone','NewNameID')">

Categories