Display items of drop down based on each other - javascript

1) I have two drop downs with exactly the same values. I want the drop down 2 to display the values based on the selection of items of drop down 1. So the selected index of drop down 2 will be equal to or more than the selected index of drop down 1. ( this code is working)
but When I add one more drop down and based on its items the other two dropdowns should behave as:
2) If I select TCD in the first Dropdown and change to value B in the second dropdown the value should be B in the third dropdown too but If I select BCD from the first dropdown it should retain the values of other two dropdown from the previous selection.( should not go back to A)
The first part is working but the second part is having issues.
Fiddle : 1) http://jsfiddle.net/wtLm4805/2/
Fiddle with three dropdowns : 2) http://jsfiddle.net/wtLm4805/3/
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
for (var i = 0; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
(i < select1.selectedIndex)
? o.disabled = true
: o.disabled = false ;
select2.appendChild(o);
}
Where am I going wrong ?

You can go somewhere along these lines
var typeValue = 'TCD'; // default initialisation
$('#Type').change(function(){
var value = $(this).val();
console.log(value);
if(value == 'TCD')
{
typeValue = 'TCD';
// change something in other selects too
}
else if(value == 'MCD')
{
typeValue = 'MCD';
}
else if(value == 'BCD')
{
$('#SELECTA').val('B');
$('#SELECTB').val('B');
typeValue = 'BCD';
}
});
$('#SELECTA').change(function(){
var value = $(this).val();
console.log(value);
if(typeValue = 'TCD')
{
$('#SELECTB').val(value);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="Type" id="Type" >
<option value="TCD">TCD</option>
<option value="MCD" >MCD</option>
<option value="BCD" >BCD</option>
</select>
<select id="SELECTA" class="SELECTA">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB" class="SELECTB" >
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>

Since you have only one element with class SELECTA and one with class SELECTB, these will always be undefined:
var select1 = document.getElementsByClassName("SELECTA")[1];
var select2 = document.getElementsByClassName("SELECTB")[1];
var select1 = document.getElementsByClassName("SELECTA")[2];
var select2 = document.getElementsByClassName("SELECTB")[2];
If you're trying to target the options, you could move the classes to the options themselves, or you could reference them like this:
document.getElementsByClassName("SELECTA")[0].options[1]
Not sure why you're deleting/adding items to the SELECTB element, but is this what you're going for?
function clickButton() {
var Type= document.getElementById('Type');
var select1= document.getElementById('SELECTA');
var select2= document.getElementById('SELECTB');
if(Type.value === 'TCD') {
for(var i = 0 ; i < select1.options.length ; i++) {
select2.options[i].disabled= i < select1.selectedIndex;
}
select2.value= select1.value;
}
else {
for(var i = 0 ; i < select2.options.length ; i++) {
select2.options[i].disabled= false;
}
}
}
<select name="Type" id="Type" onchange="clickButton()">
<option value="TCD">TCD</option>
<option value="MCD">MCD</option>
<option value="BCD">BCD</option>
</select>
<select id="SELECTA" onchange="clickButton()">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<select id="SELECTB">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>

Related

javascript select alphabetically sorting

I am trying to sort option alphabetically
My Html is
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
js
var options = $("#myOpt option");
options.detach().sort(function(a,b) {
var at = $(a).text();
var bt = $(b).text();
return (at > bt)?1:((at < bt)?-1:0);
});
options.appendTo("#myOpt");
it sorts option correctly but now instead of selected option it shows last option. My question is how to show selected option instead of last option and can it be done by another client side method? since for big list it making page slow
Try this,
var options = $("#myOpt option");
var selectedVal = '';
options.detach().sort(function(a,b) {
var at = $(a).text();
var bt = $(b).text();
if($(a).attr('selected') || $(b).attr('selected')){
selectedVal = $(a).attr('selected') ? $(a).val() : $(b).val();
return false;
}
return (at > bt)?1:((at < bt)?-1:0);
});
options.appendTo("#myOpt");
$('#myOpt').val(selectedVal);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
Don't select the 1st option to sort. var options = $("#myOpt option:not(:eq(0))");
You may use web workers to avoid browser frize if this a big list.
also, you can put it inside setTimeout to push it in event loop
$(function() {
var options = $("#myOpt option:not(:eq(0))");
options.detach().sort(function(a, b) {
var be = $(b);
var ae = $(a);
if (be.attr('selected')) {
selectedVal = be.val();
return 1;
}
if (ae.attr('selected')) {
selectedVal = ae.val();
return -1;
}
var at = ae.text();
var bt = be.text();
return (at > bt) ? 1 : ((at < bt) ? -1 : 0);
});
options.appendTo("#myOpt");
$("#myOpt").val(selectedVal);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
$(function() {
var options = $("#myOpt option");
options.detach().sort(function(a, b) {
var be = $(b);
var ae = $(a);
if (be.attr('selected')) {
selectedVal = be.val();
return 1;
}
if (ae.attr('selected')) {
selectedVal = ae.val();
return -1;
}
var at = ae.text();
var bt = be.text();
return (at > bt) ? 1 : ((at < bt) ? -1 : 0);
});
options.appendTo("#myOpt");
$("#myOpt").val(selectedVal);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
To do the sort using native JavaScript may actually give you somewhat more readable code, while taking advantage of operations (like shift/unshift) that jQuery does not implement.
The selection issue is occurring because an option detached from it's parent select cannot be selected - so you need to either select the first option again.
document.addEventListener("DOMContentLoaded", function() {
var options = $("#myOpt option").detach()
options = $.makeArray(options);
var first = options.shift();
options.sort( (a,b) => a.text.localeCompare(b.text) );
options.unshift(first);
$("#myOpt").append(options);
$("#myOpt option").eq(0).prop("selected", true)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>
You may want to simply just leave the selected element alone and just detach/sort the others, which ends up being quite a bit simpler:
document.addEventListener("DOMContentLoaded", function() {
var options = $("#myOpt option").not('[value=""]').detach();
options.sort( (a,b) => a.text.localeCompare(b.text) );
$("#myOpt").append(options);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="myOpt">
<option value="" selected data-default>Select Name</option>
<option value="3">John Snow</option>
<option value="34">Arya Stark</option>
<option value="54">Sansa Stark</option>
<option value="4">Hound</option>
</select>

Hiding an option if its selected in the other select box JavaScript

I want to hide the option in the selection box if the option is already selected in another box. I am not sure where the problem is in my code, I tried running it on different editors it didn't work. Here is my code:
<html>
<head>
<title>Currency Converter</title>
</head>
<body>
<script langauge="javascript">
function CheckDropDowns() {
ListOfSelectedCountires = [];
for (CountryNumber = 0; CountryNumber < 3; CountryNumber++) {
ListOfSelectedCountires[CountryNumber] = document.getElementById("country" + (CountryNumber + 1)).value;
}
for (algoritmCountryNumber = 0; algoritmCountryNumber < 3; algoritmCountryNumber++) {
for (countryOptions = 1; countryOptions < 5; countryOptions++) {
document.getElementById("country" + (algoritmCountryNumber + 1)).options[countryOptions].style.display = "block";
for (processedOption = 0; processedOption < 3; processedOption++) {
if (document.getElementById("country" + (algoritmCountryNumber + 1).options[countryOptions].value == ListOfSelectedCountires[processedOption]) {
document.getElementById("country" + (algoritmCountryNumber + 1)).options[countryOptions].style.display = "none";
}
}
}
}
}
</script>
<section>
<select id="country1" onchange="CheckDropDowns()">
<option value="">Choose</option>
<option value="1">Australia</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>
Convert to
<select id="country2" onchange="CheckDropDowns()">
<option value="">Choose</option>
<option value="1">Australia</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>
</section>
</body>
</html>
First determine which select needs to be filtered, then loop through the options setting display to block first(to undo the previous filter), and then if the option's value matches the selected value set it's display to none.
Edit
Above method does not work in every browser. The better HTML5 way is to set and remove the hidden attribute. I've updated the snippet.
window.CheckDropDowns = function(thisSelect) {
var otherSelectId = ("country1" == thisSelect.id) ? "country2" : "country1";
var otherSelect = document.getElementById(otherSelectId);
for (i = 0; i < otherSelect.options.length; i++) {
//otherSelect.options[i].style.display = 'block';
otherSelect.options[i].removeAttribute('hidden');
if (otherSelect.options[i].value == thisSelect.value) {
//otherSelect.options[i].style.display = 'none';
otherSelect.options[i].setAttribute('hidden', 'hidden');
}
}
}
<section>
<select id="country1" onchange="CheckDropDowns(this)">
<option value="">Choose</option>
<option value="1">Australia</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>
Convert to
<select id="country2" onchange="CheckDropDowns(this)">
<option value="">Choose</option>
<option value="1">Australia</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>
</section>
I don't know what's wrong with your code, the logic seems convoluted. You can't reliably hide options by setting their display to 'none', in some browsers they remain visible. If it was that simple, life would be easy.
You can hide options by removing them from the list, but then you have to remember where they came from so you can put them back when the selection changes.
In the following, each time an option is selected, if there's one stored it's put back and the one matching the selected option is removed. If the first option is selected, the stored one is just put back, nothing is removed.
This only depends on the two selects having the same class value, they could be related by some other value (e.g. a data-* property).
Hopefully the comments are sufficient.
var matchSelected = (function() {
// Store for "hidden" node
var nodeStore = {
sourceElement: null,
node: document.createDocumentFragment(),
index: null
};
return function(evt) {
// Get the element that got the event
var tgt = this;
// If there's a stored option, put it back
if (nodeStore.sourceElement) {
let sel = nodeStore.sourceElement;
sel.insertBefore(nodeStore.node.firstChild, sel.options[nodeStore.index]);
nodeStore.sourceElement = null;
nodeStore.node = document.createDocumentFragment();
nodeStore.index = null;
}
// If the selected option is the first one, stop here
if (tgt.selectedIndex == 0) return;
// Get all selects with the same className
var sels = document.querySelectorAll('.' + this.className);
// Get the "other" option
var other = sels[0] == this ? sels[1] : sels[0];
// Remove and keep the option on the other element that is the same
// as the selected option on the target element
nodeStore.sourceElement = other;
nodeStore.index = tgt.selectedIndex;
nodeStore.node.appendChild(other.options[tgt.selectedIndex]);
}
}());
window.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.countrySelect').forEach(
node => node.addEventListener('change', matchSelected, false)
);
}, false);
<select id="country1" class="countrySelect">
<option value="" selected>Choose</option>
<option value="1">Australia Dollar</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>
Convert to
<select id="country2" class="countrySelect">
<option value="" selected>Choose</option>
<option value="1">Australia Dollar</option>
<option value="2">Indonesian Rupiah</option>
<option value="3">Chinese Yaun</option>
<option value="4">Japanese Yen</option>
</select>

How to get the value of option with attribute selected

I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>

How to get selected values in SumoSelect dropdown?

I am using the SumoSelect dropdown for multiselect options. But i cannot get the selected values array.
Below the sample code :
<script type="text/javascript">
$(document).ready(function () {
window.testSelAll = $('.testSelAll').SumoSelect({okCancelInMulti:true, selectAll:true });
$('.btnOk').on('click', function(){
var obj = [];
$('option:selected').each(function () {
obj.push($(this).index());
alert("Selected Values=="+$(this).val());
});
for (var i = 0; i < obj.length; i++) {
$('.testSelAll')[0].sumo.unSelectItem(obj[i]);
}
});
});
</script>
<select multiple="multiple" placeholder="Share Your Friends" onchange="console.log($(this).children(':selected').length)" class="testSelAll">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
<option value="porsche">Porche</option>
<option value="ferrari">Ferrari</option>
<option value="mitsubishi">Mitsubishi</option>
</select>
If you want the selected values instead of the text, just change .text() to .val().
If you want to get the array, see below with working example at the bottom.
jQuery
$(document).ready(function() {
$('.testSelAll').SumoSelect({
okCancelInMulti: true,
selectAll: true
});
$('.btnOk').on('click', function() {
var obj = [],
items = '';
$('.testSelAll option:selected').each(function(i) {
obj.push($(this).val());
$('.testSelAll')[0].sumo.unSelectItem(i);
});
for (var i = 0; i < obj.length; i++) {
items += ' ' + obj[i]
};
alert(items);
});
});
HTML
<select multiple="multiple" class="testSelAll">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Working JSFIDDLE
You can get them from underlying hidden select element.
using jquery eg.
$('.select1 option:selected')
I think the cleanest way to do this. Is to take advantage of html5 select element underlying SumoSelect.
HTML
<select multiple="multiple" class="testSelAll" id="multi-select">
<option value="car1">Volvo</option>
<option value="car2">Saab</option>
<option value="car3">Mercedes</option>
<option value="car4">Audi</option>
</select>
Javascript
var values = $('#multi-select').val();
This line will return a string list of the values selected.

Prototype - How to deselect the selected value from a dropdown

How do I deselect the selected value from a dropdown list using Prototype.
From
<select id=“mylist” MULTIPLE >
<option value=“val-1”>Value 1</option>
<option value=“val-2” SELECTED>Value 2</option>
<option value=“val-3”>Value 3</option>
</select>
To
<select id=“mylist” MULTIPLE >
<option value=“val-1”>Value 1</option>
<option value=“val-2”>Value 2</option>
<option value=“val-3”>Value 3</option>
</select>
Thanks for any help in advance.
I'm not sure how to do it in prototype, but I can do it in JavaScript.
For a regular select, set yourSelectElement.selectedIndex = -1.
For a multiple select, you can just ctrl+click on the selected item, but you can do it programmatically as well. See link.
http://jsfiddle.net/kaleb/WxJ9R/
You can't : you'll have to add an empty option
<option></option>
and then
$$("#mylist option[selected]")[0].selected = false;
$$("#mylist option")[0].selected = true;
On the event of the second list being selected...
Event.observe('secondlist', 'change', function(){
if (this.selectedIndex >= 0)
$$('#mylist option[selected]').invoke('writeAttribute', 'selected', false);
});
I found the following code worked well:
var options = $$('select#mylist option');
var len = options.length;
for (var i = 0; i < len; i++) {
options[i].selected = false;
}

Categories

Resources