How to make one select being depending to another select? - javascript

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.

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

Dynamically update a dropdown list based on another dropdown list?

I have a dropdown list with id='apha' with three options and their values are comma separated.
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
Another dropdown beta with values. Based on which option is selected in alpha those values should be there in second dropdown beta.
<select class="browser-default" id="beta">
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>
So if One is selected from alpha dropdown. Only values of aplha - a,b,c should be present in beta dropdown - First Second Third
What i have tried:
Without comma separated in values
$('#alpha').on('change', function () {
$('#alpha').html('');
if ($('#alpha').val() == "One") {
$('#alpha').append('<option value="a">First</option>');
$('#alpha').append('<option value="b">Second</option>');
$('#alpha').append('<option value="c">Third</option>');
}
});
You can use split(',') to split values then using for-loop you can get values from split array and finally use $("#beta option[value=" + vals + "]").show() to show options where values matches.
Demo Code:
$("#alpha").on("change", function() {
var values = $(this).val().split(',') //split value which is selected
$("#beta option").hide() //hide all options from slect box
//loop through values
for (var i = 0; i < values.length; i++) {
var vals = values[i]
$("#beta option[value=" + vals + "]").show()//show that option
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
<select class="browser-default" id="beta">
<option selected="selected" value="">--select one-- </option>
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>
Vanilla JS
const beta = document.getElementById('beta');
const betaOpts = [...beta.children];
document.getElementById('alpha').addEventListener(
'change',
(e) => {
beta.innerHTML = betaOpts.filter(
o => e.target.value.includes(o.value)
).map(o => o.outerHTML).join('')
})
<label>Alpha</label>
<select class="browser-default" id="alpha">
<option value="a,b,c">One</option>
<option value="d">Two</option>
<option value="e,f">Three</option>
</select>
<label>Beta</label>
<select class="browser-default" id="beta">
<option value="a">First</option>
<option value="b">Second</option>
<option value="c">Third</option>
<option value="d">Fourth</option>
<option value="e">Fifth</option>
<option value="f">Sixth</option>
</select>

How can maintain as selected the second option in a drop down with random values?

I want to always maintain how to select the second option for its drop downs. The point here is that the value is random:
MyBrowser.document.getElementById("multipleCat_1").Value = "RANDOMVALUE"
How do I select the second option in a drop down menu?
HTML:
<select id="multipleCat_1">
<option value="-1">Select</option>
<option value="RANDOMVALUE">Second Option"</option>
</select>
You can use selectedIndex as below:
document.querySelectorAll('#multipleCat_1 > option')[1].value = 'Got you!';
document.getElementById('multipleCat_1').selectedIndex = 1
console.log(document.getElementById('multipleCat_1').value)
<select id="multipleCat_1">
<option value="-1">Select</option>
<option value="RANDOMVALUE">Second Option"</option>
</select>
<select id="multipleCat_1">
<option value="A">AAA</option>
<option value="B">BBB</option>
<option value="C">CCC</option>
</select>
var options = document.querySelectorAll('#multipleCat_1 > option');
document.getElementById('multipleCat_1').value = options[1].value;

multiple select boxes with same options - require unique selection

I have a form with 3 select boxes. Each select box has the same options. I want to require that you have to select a different option for each select box. For example, let's say the options are "cat", "dog" and "bird". If someone selects "bird" in the first select box, I want to disable or hide that option from the other two boxes. If they change their selection, then "bird" will be enabled or unhidden again.
<select id="box1">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
I assume I can do this with jquery onchange but I'm not sure how to require the unique selection across different select boxes.
$('select').on('change', function() {
// If option is selected, disable it in all other select boxes. If option is deselected, reenable it in all other select boxes.
})
Thanks for your help!
1) Top To Bottom Priority Approach
The flow must be top to bottom. This also means when ever the user changes the dropdown value all the next dropdown's which come after it must be reset. Having said this, here is my code snippet.
HandleDropdowns($('#box1')); //initially call this function to handle the dropdowns by passing the first dropdown as parameter
$('select').on('change', function() {
HandleDropdowns($(this)); // handle all dropdowns on any change event.
});
function HandleDropdowns(element) {
var $element = element;
var value = $element.val();
$element.nextAll().val(''); //using nextAll lets reset all the following dropdowns
$element.nextAll().attr('disabled', 'disabled'); //disable all the following dropdowns.
HandleOptions(); // call this function to toggle the options
if (value.length) {
$element.next().removeAttr('disabled'); // only if this dropdown has some selection enable the next dropdown.
}
}
function HandleOptions() {
$('option').removeAttr('disabled'); //reset all the options to be available
$.each($('select'), function() { //loop from top to bottom and disable the options one by one.
var value = $(this).val();
if (value.length) {
$(this).nextAll().find('option[value="' + value + '"]').attr('disabled', 'disabled');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="box1">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
2) All Select Box With Same Priority Approach
In this approach when ever the user selects a value we check if any other dropdown has the same value, If yes reset it else do nothing. Below is a working sample.
$('select').on('change', function() {
HandleDropdowns($(this));
});
function HandleDropdowns(element) {
var $element = element;
var value = $element.val();
$.each($('select').not($element), function() { //loop all remaining select elements
var subValue = $(this).val();
if (subValue === value) { // if value is same reset
$(this).val('');
console.log('resetting ' + $(this).attr('id')); // demo purpose
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="box1">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
Try this
$('select').on('change', function () {
$("select").find("option").removeAttr("disabled");
$("select").not(this).find("option[value=" + $(this).val() + "]").attr("disabled", "disabled");
});
You can use onchange listener and evaluate the results simultaneously. Also add an reset button cause once three get selected, it becomes bottle neck case.
The working code is given below
function changeSelect(elements) {
var values = {};
elements.forEach(function(item){
values[item.id] = item.value;
});
elements.forEach(function(item){
for(var i = 0; i < item.children.length; i++) {
for(ids in values) {
if(item.id != ids && item.children[i].value == values[ids]) {
item.children[i].style.display = 'none';
}
}
}
});
}
function resetSelection(elements) {
elements.forEach(function(item){
item.value = '';
for(var i = 0; i < item.children.length; i++) {
item.children[i].style.display = '';
}
});
}
var box1 = document.getElementById('box1');
var box2 = document.getElementById('box2');
var box3 = document.getElementById('box3');
var boxArray = [box1, box2, box3];
boxArray.forEach(function(item){
item.addEventListener('change', changeSelect.bind(undefined,boxArray));
});
document.getElementById('reset').addEventListener('click', resetSelection.bind(undefined,boxArray));
<select id="box1">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box2">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<select id="box3">
<option value="">Select An Option</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="bird">Bird</option>
</select>
<button id="reset">Reset</button>

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