Js dropdown depends of an other dropdown - javascript

Hey guys simple question how can I display in the second dropdown information that depends of the first one.
Example. I have this:
var option = document.getElementById("second_dropdown").getElementsByTagName("option");
for (var j = 0; j < option.lenght; j++) {
option[j].disabled = true;
}
<!-- DROPDOWN 1 -->
<select id="first_dropdown" name="first_d">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<!-- DROPDOWN 2 -->
<select id="second_dropdown" name="second_d">
<optgroup label="1">
<option value="100">blabla</option>
<option value="101">blabla</option>
<option value="102">blabla</option>
</option>
<optgroup label="2">
<option value="103">blabla</option>
<option value="104">blabla</option>
<option value="105">blabla</option>
</option>
<optgroup label="3">
<option value="106">blabla</option>
<option value="107">blabla</option>
<option value="108">blabla</option>
</option>
<select>
And I would like to display in dropdown 2 only the optgroup that has been selected in dropdown 1 ...
I really don't know about js so I hope that i explained it well and thanks in advance :)
But here I only disable all (and I want to disable only what's not selected in dropdown one) and I don't want to disable but I want to undisplay.

Loop through optgroup of second <select> and in loop check if value of first select is equal to label of optgroup remove disabled of it.
document.querySelector("#first_dropdown").onchange = function(){
var val = this.value;
document.querySelectorAll("#second_dropdown optgroup").forEach(function(ele){
ele.disabled = ele.label != val
});
};
<select id="first_dropdown" name="first_d">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="second_dropdown" name="second_d">
<optgroup label="1">
<option value="100">blabla</option>
<option value="101">blabla</option>
<option value="102">blabla</option>
</optgroup>
<optgroup label="2">
<option value="103">blabla</option>
<option value="104">blabla</option>
<option value="105">blabla</option>
</optgroup>
<optgroup label="3">
<option value="106">blabla</option>
<option value="107">blabla</option>
<option value="108">blabla</option>
</optgroup>
<select>
Also you should change display property of element if you want to show/hide optgroup
document.querySelector("#first_dropdown").onchange = function(){
var val = this.value;
document.querySelectorAll("#second_dropdown optgroup").forEach(function(ele){
ele.style.display = ele.label==val ? "block" : "none";
});
};
Also you can do this work simplify using jquery
$("#first_dropdown").change(function(e){
$("#second_dropdown optgroup").css("display", function(){
return this.label==e.target.value ? "block" : "none";
});
});

You can try the following way:
var firstDD = document.getElementById('first_dropdown');
firstDD.addEventListener('change',changeDD);
function changeDD(){
var fValue = firstDD.value;
document.querySelectorAll('#second_dropdown > optgroup').forEach(function(el){
if(el.label != fValue )
el.style.display='none';
else
el.style.display='block';
});
document.querySelector('#second_dropdown').value = "";
}
changeDD(firstDD);
<select id="first_dropdown" name="first_d">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<select id="second_dropdown" name="second_d">
<optgroup label="1">
<option value="100">blabla</option>
<option value="101">blabla</option>
<option value="102">blabla</option>
</optgroup>
<optgroup label="2">
<option value="103">blabla 21</option>
<option value="104">blabla</option>
<option value="105">blabla</option>
</optgroup>
<optgroup label="3">
<option value="106">blabla</option>
<option value="107">blabla</option>
<option value="108">blabla</option>
</optgroup>
<select>

Related

Remove duplicate empty values from select tag

I have below select tag
<select id="subCategorySelected">
<option value="Select Sub Category">Select Sub Category</option>
<option value=""></option>
<option value="subcat1">sub cat 1</option>
<option value="subcat2">sub cat 2</option>
<option value=""></option>
<option value="subcat4">sub cat 4</option>
<option value=""></option>
</select>
I need to filter items in the tag and remove all duplicate elements in below way
<select id="subCategorySelected">
<option value="Select Sub Category">Select Sub Category</option>
<option value=""></option>
<option value="subcat1">sub cat 1</option>
<option value="subcat2">sub cat 2</option>
<option value="subcat4">sub cat 4</option>
</select>
I have tried in below ways as suggested in some other question but both are not working
1)
var map = {};
$('#subCategorySelected').each(function () {
if (map[this.value]) {
$(this).remove()
}
map[this.value] = true;
})
2)
$("#subCategorySelected").val(function(idx, val) {
$(this).siblings('[value="'+ val +'"]').remove();
});
Thanks in advance
Check this out
$(document).ready(function(){
$('#subCategorySelected option').each(function(index,val){
var value=$(this).val();
$(this).siblings('[value="'+ value +'"]').remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="subCategorySelected">
<option value="Select Sub Category">Select Sub Category</option>
<option value=""></option>
<option value="subcat1">sub cat 1</option>
<option value="subcat2">sub cat 2</option>
<option value=""></option>
<option value="subcat4">sub cat 4</option>
<option value=""></option>
</select>
If you know the only duplicates are empty values you could just do:
$("#subCategorySelected option[value='']").slice(1).remove();
otherwise your first method works, just change the selector to:
$("#subCategorySelected option")

jQuery Select box multiple option get value and match values

I have same classname multi select box with same values in body, what I want if use chose value 1 from first or any select box then that value 1 on all other select box option will disable so user can't choose the same value in other multi select box.
<select name="mySel" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
<select name="mySel" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
This need to achieve via javascript or jQuery,
So you're likely going to get downvotes. You haven't actually shown that you've tried anything, you have only given us the HTML and asked that we solve your problem.
That said, I like to sink my teeth into easy problems, as this is. What you're wanting to do is, in each select, listen for the change event. When that triggers, get the value of the selected option, and disable any option with that value in any other selects. Take a look at the following:
$(function() {
/********
* Function to disable the currently selected options
* on all sibling select elements.
********/
$(".myselect").on("change", function() {
// Get the list of all selected options in this select element.
var currentSelectEl = $(this);
var selectedOptions = currentSelectEl.find("option:checked");
// otherOptions is used to find non-selected, non-disabled options
// in the current select. This will allow for unselecting. Added
// this to support extended multiple selects.
var otherOptions = currentSelectEl.find("option").not(":checked").not(":disabled");
// Iterate over the otherOptions collection, and using
// each value, re-enable the unselected options that
// match in all other selects.
otherOptions.each(function() {
var myVal = $(this).val();
currentSelectEl.siblings(".myselect")
.children("option[value='" + myVal + "']")
.attr("disabled", false);
})
// iterate through and disable selected options.
selectedOptions.each(function() {
var valToDisable = $(this).val();
currentSelectEl.siblings('.myselect')
.children("option[value='" + valToDisable + "']")
.attr("disabled", true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="mySel" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
<select name="mySel2" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
<select name="mySel3" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
<select name="mySel4" class="myselect" multiple="multiple">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
Edited the above code to support multiple selects. Actually, it wasn't so much an issue of multiple selects, as I was doing a very lazy handling of unselecting options. Now, when the user is selecting or de-selecting options in any select, only the non-disabled options in that select are used: the (":checked") to disable that option in all other selects, and the .not(":checked") to re-enable any options that the user has somehow unselected.
Try this code , it should do the job:
using Not selector and for each to iterate on other select options:
$(document).ready(function() {
$('.myselect:first').change(function() { // once you change the first select box
var s = $('.myselect:first option:selected').val(); // get changed or clicked value
others = $(':not(.myselect:first) >option'); //select other controls with option value
others.each(function() {
if (this.value == s) // for example if you click on 1 the other controls will get 1 disabled
$(this).attr('disabled', 'disabled').siblings().removeAttr('disabled');
// remove disabled from others if you click something else
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="myselect" multiple="multiple" name="mySel">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>
<select class="myselect" multiple="multiple" name="mySel">
<option value="val1">option 1</option>
<option value="val2">option 2</option>
<option value="val3">option 3</option>
<option value="val4">option 4</option>
</select>

Select Dropdown based on the partial value in dropdown value field

I have a scenario where i have to select the drop value based on querystring.
Query string could be likeq=c-1 q=c-2 q=p-5
and value in drop-down could be value="8-P-5" value="5-G-0" value="7-P-7"
How can i select the drop-down value based on query-string
Is it possible to do it from Code-behind C# or jquery is easy solution.
<select name="ctl00$ContentPlaceHolder1$ddlOptionGroup" id="ContentPlaceHolder1_ddlOptionGroup" class="form-control">
<option value="1-C-1">Item 1</option>
<option value="4-C-2">Item 2</option>
<option value="5-G-0">Item 3</option>
<option value="7-P-7">Item 4</option>
<option value="8-P-5">Item 5</option>
<option value="10-C-4">Item 6</option>
<option value="3-P-0">Item 7</option>
<option value="2-P-0">Item 8</option>
<option value="6-G-0">Item 9</option>
</select>
If query-string is q=c-2 then this should be selected <option value="4-C-2" selected>Item 2</option>
If you are open for a JavaScript/jQuery solution you can take the window.location.search and then use a jQuery selector to find the option based on a contains condition in a specific select tag.
Do note that this assumes the value that comes in your q is uniquely identifiable in a value property of your select element. In your current dataset q=p-0 will have both Item 7 AND Item 8 match. As you didn't provide a business rule for that case I left that here untouched.
Here is a snippet that demonstrate this:
// use window.location.search
var search = '?q=p-5'; // window.location.search;
// handle possible search for this value ?foo=bar&q=p-5#fragment
var parms = search.substr(1).split('&');
for(var i=0; i< parms.length;i++)
{
var keyValue= parms[i].split('=');
if (keyValue[0] === "q" && keyValue.length > 0) {
var value = keyValue[1].split('#');
$('select > option[value*="' + value[0].toUpperCase() + '"]').prop('selected',true);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="ctl00$ContentPlaceHolder1$ddlOptionGroup" id="ContentPlaceHolder1_ddlOptionGroup" class="form-control">
<option value="1-C-1">Item 1</option>
<option value="4-C-2">Item 2</option>
<option value="5-G-0">Item 3</option>
<option value="7-P-7">Item 4</option>
<option value="8-P-5">Item 5</option>
<option value="10-C-4">Item 6</option>
<option value="3-P-0">Item 7</option>
<option value="2-P-0">Item 8</option>
<option value="6-G-0">Item 9</option>
</select>
for (int i = DropDownList1.Items.Count-1; i >0 ; i--)
{
if (DropDownList1.Items[i].Value.Contains("C-2"))
{
DropDownList1.Items[i].Selected = true;
break;
}
}
or you can do it by Linq syntax
DropDownList1.Items.Cast<ListItem>()
.Where(x => x.Value.Contains("C-2"))
.LastOrDefault().Selected = true;

Jquery disallow same value from multiple select lists

I need to make sure that when a value is selected in one of the lists, it cannot be selected in any of the others. Can this be done with jQuery, or do I need to create a validator that does not allow selection of the same value?
I have multiple select lists which are basically numbers only, i.e.
<select id="101_1">
<option value="0">0</option>
<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>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
<select id="101_2">
<option value="0">0</option>
<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>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
<select id="101_1">
<option value="0">0</option>
<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>
<option value="6"> 6</option>
<option value="7"> 7</option>
....
<option value="50"> 50</option>
</select>
I have gotten the following code to work for one of my colleagues :
HTML :
<h3>List 1</h3>
<select id="select1">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<h3>List 2</h3>
<select id="select2">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
<h3>List 3</h3>
<select id="select3">
<option value="null">-- select --</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
</select>
JS with jQuery :
$(document).ready(function() {
var selectState = {
'select1': 'null',
'select2': 'null',
'select3': 'null'
};
$('select').change(function() {
var selectId = $(this).attr('id');
var selectedOptionValue = $(this).val();
// for each other select element
$('select[id!="' + selectId + '"]').each(function(index) {
// enable the old option
$(this).find('option[value="' + selectState[selectId] + '"]').removeAttr('disabled');
if (selectedOptionValue !== 'null') { // if selected a real option
// disable the new option
$(this).find('option[value="' + selectedOptionValue + '"]').attr('disabled', 'disabled');
}
});
selectState[selectId] = selectedOptionValue; // update the new state at the end
});
});
And here is a CodePen
I opted to hide the option tag instead of remove as I suggested. Here is a complete working html file. I was going to post it on jsfiddle, but for some reason it wouldn't work. Be very aware of copy/paste errors in the .change handlers. Spent some time myself wondering why it wasn't working, but it was a copy/paste error.
Note that this code only works if every select tag has the same options. But, it works dynamically if you add or remove options later, while keeping them in sync as noted.
If you need it to work with lists with only some of the same options, you will be stuck dealing with having IDs on the options and then working the hiding/unhiding based on that instead of indexing into the children, but the basic mechanics are the same.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<style type="text/css">
.gone {display: none;}
</style>
<script type="text/javascript">
$(document).ready(function() {
// hides the option selected in the others
var hideValue = function(oldval, val, options, others) {
var unhideChild = -1;
var hideChild = -1;
// find which child to hide in the others
// also find the value we change from and unhide it
for (var i=1; i<options.length; i++) {
var optval = $(options[i]).val();
console.log(optval);
if (optval == val) {
hideChild = i;
}
if (optval == oldval) {
unhideChild = i;
}
}
if (unhideChild == -1 && oldval != "None") {
console.log("uh oh");
return;
}
if (hideChild == -1 && val != "None") {
console.log("uh oh");
return;
}
// hide them using the passed in selectors
for (var j=0; j<others.length; j++) {
if (oldval != "None") {
console.log("unhiding: " + others[j] + " v: " + unhideChild);
$($(others[j]).children()[unhideChild]).removeClass("gone");
}
if (val != "None") {
console.log("hiding: " + others[j] + " v: " + hideChild);
$($(others[j]).children()[hideChild]).addClass("gone");
}
}
}
// we need to keep track of the old values so we can unhide them if deselected
var val1 = "None";
var val2 = "None";
var val3 = "None"
$('#101_1').change(function() {
var opts = $('#101_1').children();
var v = $('#101_1').val();
hideValue(val1, v, opts, ["#101_2", "#101_3"]);
val1 = v;
});
$('#101_2').change(function() {
var opts = $('#101_2').children();
var v = $('#101_2').val();
hideValue(val2, v, opts, ["#101_1", "#101_3"]);
val2 = v;
});
$('#101_3').change(function() {
var opts = $('#101_3').children();
var v = $('#101_3').val();
hideValue(val3, v, opts, ["#101_2", "#101_1"]);
val3 = v;
});
});
</script>
</head>
<body>
<select value="None" id="101_1">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select value="None" id="101_2">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select value="None" id="101_3">
<option value="None">None</option>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>
Also, if you need the "None" value to not be there, remove it. Then just start the select ta 101_1 having 0 selected, 101_2 with 1 selected etc. Then make sure to trigger the change handler. Also, without the None option, the for loop needs to start with i=0.
So basically add this to the end of the script and make sure var i starts at 0 instead of 1.
$('#101_1').val('0');
$('#101_2').val('1');
$('#101_3').val('2');
$('#101_1').trigger('change');
$('#101_2').trigger('change');
$('#101_3').trigger('change');

Hide/show the selected option on a secondary select

I have two <select> elements with different IDs.
When the user selects a value from the first select box, I want the second select box to only display connected values.
My code:
<select id="ExtraField_1" name="ExtraField_1">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
</select>
<select id="ExtraField_2" name="ExtraField_2">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
<option value="13">test13</option>
<option value="14">test14</option>
<option value="15">test15</option>
<option value="16">test16</option>
<option value="17">test17</option>
<option value="18">test18</option>
<option value="19">test19</option>
<option value="20">test20</option>
</select>
So when user selects "test1" from first select boxm he will see only "test2", "test3" and "test4" on the second select box; "test2" from first will show "test6", "test7" and "test8" in the second box.
How can I use JavaScript to resolve this problem?
If you can use jQuery then you can always just clear and append the options to the second select.
$('#ExtraField_1').change(function(){
$('#ExtraField_2').find('option').remove()
if($(this).val() == '1'){
$('#ExtraField_2').append($("<option </option>").attr('value','2').text('test2'));
$('#ExtraField_2').append($("<option></option>").attr('value','3').text('test3'));
$('#ExtraField_2').append($("<option></option>").attr('value','4').text('test4'));
}
if($(this).val() == '2'){
$('#ExtraField_2').append($("<option></option>").attr('value','5').text('test5'));
$('#ExtraField_2').append($("<option></option>").attr('value','6').text('test6'));
$('#ExtraField_2').append($("<option></option>").attr('value','7').text('test7'));
}
});
​
http://jsfiddle.net/8XVuv/2/
using only javascript is a bit more complicated but I would still take the same approach.
function createOption(otext,oValue){
var newOption = document.createElement('option');
newOption.text = otext;
newOption.value = oValue;
return newOption;
}
function clearSelect(theSelect){
for(var i = 0;i <= theSelect.options.length+1;i++)
{
theSelect.remove();
}
}
function onSelect(theSelect){
var nextSelect = document.getElementById('ExtraField_2');
clearSelect(nextSelect);
var selected = theSelect.options[theSelect.selectedIndex];
if(selected.value == 1){
nextSelect.add(createOption('test2','2'));
nextSelect.add(createOption('test3','3'));
nextSelect.add(createOption('test4','4'));
}
if(selected.value == 2){
nextSelect.add(createOption('test5','5'));
nextSelect.add(createOption('test6','6'));
nextSelect.add(createOption('test7','7'));
}
}
with html:
<select id="ExtraField_1" name="ExtraField_1" onchange="javascript: onSelect(this);" >
<option value="0">Select a test..</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
<option value="4">test4</option>
<option value="5">test5</option>
<option value="6">test6</option>
<option value="7">test7</option>
<option value="8">test8</option>
<option value="9">test9</option>
<option value="10">test10</option>
<option value="11">test11</option>
<option value="12">test12</option>
</select>
<select id="ExtraField_2" name="ExtraField_2">
<option value="0">Select from the left</option>
</select>​
as you can see it still does what you expect but you are not hiding options.
http://jsfiddle.net/upKzW/13/
$('#ExtraField_1').change(function() {
$('#ExtraField_2').val(this.value);
});
http://jsfiddle.net/judearasu/rF8G6/

Categories