Disable Drop Down Options Once Chosen In Other Dropdown - javascript

I have 12 drop downs input areas, 1 for each of the months of the year. Each drop down has the choice of the same 24 options.
I need to make it so that, for example, if in the January drop down box you chose option #4, that option #4 cannot be selected in any of the other drop down menus. It would still be in the drop down, but would just be disabled.
This would have an ajax trigger to check the value against the other drop downs and dynamically change the other drop down menus.
Is there a loop I can do to check and disable these values dynamically without having to make a lot of if statements?

You can use jQuery to find the option element in all other dropdowns (in my example, designated by a certain class...and can easily be changed to another selector - I thought the selector "select" was too broad), and then disable the actual option element by using .prop("disabled", true). But it's a little more tricky than this, as you need to keep track of the previous selected value to enable the dropdown again when a different value is chosen. Here's an example that will hopefully help:
http://jsfiddle.net/p5Arj/
$(document).ready(function () {
$(".test").each(function () {
var $self = $(this);
$self.data("previous_value", $self.val());
});
$(".test").on("change", function () {
var $self = $(this);
var prev_value = $self.data("previous_value");
var cur_value = $self.val();
$(".test").not($self).find("option").filter(function () {
return $(this).val() == prev_value;
}).prop("disabled", false);
if (cur_value != "") {
$(".test").not($self).find("option").filter(function () {
return $(this).val() == cur_value;
}).prop("disabled", true);
$self.data("previous_value", cur_value);
}
});
});
So this disables all other dropdowns' same options when you choose one, and makes sure that when you choose another, the previous one is enabled in all other dropdowns. For example, choose "3" in the first dropdown...look at the second dropdown - see that "3" is disabled...go back to the first dropdown and choose "1"...look at the second dropdown - see that "3" is enabled again but "1" is disabled. That's what the use of .data is for in my code.
Of course, you can replace the use of value with selectedIndex if you are 100% sure that all of the options will be the same for each select in question.

http://jsfiddle.net/Rk5e9/9/
Only about 10 lines, and no ajax!
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
Script:
$(document).ready(function(){
$('.unique-value').focus(function(){
var val = $(this).val();
$(this).attr('data-current-value', val);
});
$('.unique-value').change(function(){
var val = $(this).val();
if(val != -1)
$('.unique-value option[value=' + val + ']').attr('disabled', 'disabled');
var oldval = $(this).attr('data-current-value');
$('.unique-value option[value=' + oldval + ']').removeAttr('disabled');
});
});​

I think this would be the shortest solution:
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
and the jquery code:
$(document).on('change', '.select-attendee', function(){
$current=$(this);
$(".select-attendee").not($current).children("option[value='"+$current.val()+"']").attr('disabled', "disabled");
});

Assuming you had a dropdown for each month, and an option for each week.
<select class="month" id="october">
<option class="week" value="week1">Week One</option>
<option class="week" value="week2">Week Two</option>
</select>
Lets say you select a week, and you listen for the event.
$(".month").change(function(event) {
// Get the week just selected.
var selectedWeek = $(this).children(".week:selected").val();
// Enabled all weeks before disabling the selected week.
$("option.week").removeAttr("disabled");
// Disable all week options matching this selection.
$("option.week[value="+selectedWeek+"]").attr("disabled", "disabled");
});

Related

How should i get previous selected option automatically in dropdown in javascript

In javascript, in a dropdown menu if we select one option and in that dropdown how can I get a dropdown option which had selected previous option automatically on current option (if that current option fails on certain condition).
As you've already discovered, there is no way to get the previously selected value when the dropdown is changed directly from the dropdown itself.
The best option is to store the currently selected value, my preference is via a data- attribute.
So if for example you have a select like the following...
<select>
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
You would include the currently selected value as a data-previousvalue attribute... this would be part of the code that creates the control in the first place...
<select data-previousvalue="1">
<option value="1" selected>One</option>
<option value="2">Two</option>
</select>
Then when you change the select, you can check at the current value and if necessary reset it back to that stored one.
In the following example, if you select the third item Three (bad) it will automatically take you back to the previously selected option...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
And if you have jquery available...
$(function(){
$("select").on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select data-previousvalue="4">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you can't add the data attribute to the control at the point of render, then you can also set it on the page load...
window.addEventListener("load", function() {
// Get the dropdown
var dd = document.getElementsByTagName("select")[0];
// Set the currently selected value into the attribute
dd.setAttribute("data-previousvalue", dd.value);
// When the dropdown changes
dd.addEventListener("change", function(){
// If it's a bad one
if (dd.value == "3") {
// Reselect the previous value
dd.value = dd.getAttribute("data-previousvalue");
}
// Now store the value for the next time
dd.setAttribute("data-previousvalue", dd.value);
});
});
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
If you have jquery available to you...
$(function(){
$("select")
.each(function(i,v) {
var $dd = $(this);
$dd.data("previousvalue", $dd.val());
})
.on("change", function(){
var $dd = $(this);
// If it's a bad one
if ($dd.val() == "3") {
// Reselect the previous value
$dd.val($dd.data("previousvalue"));
}
// Now store the value for the next time
$dd.data("previousvalue", $dd.val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three (bad)</option>
<option value="4" selected>Four</option>
</select>
You can do it setting element.val(previousStatus)
// Your changing value should assign on adStatus
// May be its come from database(previous status) or depends on user activity
let adStatus = 'Unfriendly';
$('#AdblockType').val(`${adStatus}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="AdblockType">
<option value="Friendly">Friendly</option>
<option vlaue="Unfriendly">Unfriendly</option>
</select>

I have two select boxes. I want to enable second select box only if i click a particular option in first select box [duplicate]

I have two dynamic dropdowns but both dropdown's value and options are same. What I want that if user select 'apple' from first dropdown then the second dropdown's apple option will be disabled (using javascript). In short user can not select same value from both.
//first drop down
<select name="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
//second dropdown
<select name="fruit2">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
I have tried with jQuery:
function witness()
{
var op=document.getElementById("witness1").value;
$('option[value='+op+']').prop('disabled', true);
}
But with this both dropdown's value are disabled and if I select mango then apple will not enabled it remains disabled. I know I did not pass id so both dropdown value are disabled but where should i pass ?
If user select apple then in second dropdown apple will be disabled, I want to do this using Javascript or jQuery.
Fiddle: https://jsfiddle.net/3pfo1d1f/
To get the functionality you're after, you need to hook into the change event on the first dropdown, in order to disable the matching element in the second drop-down.
I also initialised the first element in the second dropdown as disabled ( as this chosen by default in the first dropdown)
Used jquery as you are:
HTML:
<!-- first dropdown -->
<select id="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<br /> <br />
<!-- second dropdown -->
<select id="fruit2">
<option value="1" disabled>Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
$('#fruit1').on( "change", function() {
var op = $( this ).val();
$('#fruit2 option').prop('disabled', false);
$('#fruit2 option[value='+op+']').prop('disabled', true);
});
This should still work, no matter how many options you have in both the dropdowns
Try this out:
HTML:
<select id='fruit1' onchange="witness();">
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<select id='fruit2'>
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
function witness(){
$("#fruit2 option").each(function(){
if($("#fruit1 option:selected").val() == $(this).val())
$(this).attr("disabled", "disabled");
else
$(this).removeAttr("disabled");
});
}
You can see a working exemple here:
https://jsfiddle.net/mqjxL4n0/
<select name="firstselect" id="firstselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<select name="secondselect" id="secondselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<script>
$(document).ready(function(){
$('#firstselect').change(function(){
var firstselected = $(this).val();
if(firstselected ){
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
if($(this).val()==firstselected )
$(this).prop('disabled', true);
});
}
else {
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
});
}
});
});
</script>

When one dropdown is selected then the same option is selected in a different dropdown

I have two dropdowns and I want to make it whenever someone selects something in one dropdown the same thing is selected in the other dropdown. I can't get it to work when I select an option in the first dropdown then it doesn't select the same option in the other dropdown.
Here's the formula
$( function() {
$("input[name='FirstFlangeTypeDrop']").on("change", function(e) {
var newValue = e.target.value;
$("input[name='SecondFlangeTypeDrop'][value='" + newValue + "']").prop("selected", true);
});
});
Your question is a bit unclear to me. But I think this is what you are looking for.
$(function() {
$("select[name='FirstFlangeTypeDrop']").on("change", function(e) {
var newValue = $(this).val(); // get selected value
$("select[name='SecondFlangeTypeDrop']").val(newValue); // set selected value
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="FirstFlangeTypeDrop">
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<select name="SecondFlangeTypeDrop">
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>

jquery get current selected value from multiple

I have select drop down where I use array sign in name like
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Now I need to get current (last) selected value from drop down on change event.
What I have tried so far is
var clicked = $('#service_id option:selected').last().val();
alert(clicked);
//also tried as
//$(this).closest('select').find('option').filter(':selected:last').val();
//and this is tried too
// $(this).val();
// this.value;
All these giving me wrong value when multi select.
What I need
If select four then next select one it should alert 1 (remember when multi selection).
If select three and then next select four then it should alert 4
In brief ALWAYS need Clicked option's value even in multi select
** Not possible to remove array sign from name services[]
There is no native way, but you could save the order of the options clicked, then get the last.
ie, against a data attribute on the select:-
$('#service_id option').click(function() {
var values = $(this).parent().data('values') || [];
var index = values.indexOf(this.value);
index >= 0 ? values.splice(index, 1) : values.push(this.value);
$(this).parent().data('values', values);
});
$('#service_id').click(function() {
var values = $(this).data('values');
console.log(values);
var last = values[values.length - 1];
console.log('last:' + last);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Try this demo
$(function(){
var last_selected;
$("#service_id option").click(function(){
if($(this).is(":selected")) {
last_selected = $(this).attr('value');
}
$("#result").html(last_selected);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
<p>Last selected : <span id="result"></span></p>
So you just want to get the last selected element?
Just create a variable to store the last selected element in each option click as shown by this demo:
var currLast = null;
$('#service_id').children().on('click', function(){
var val = $(this).val();
if (currLast === val) { // do nothing if current selected is the same elem
return;
}
currLast = val;
console.log(currLast)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>

JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.
I have
<select id="mySelect">
<option value="ps">Please Select</option>
<option value="ab">Fred</option>
<option value="fg">George</option>
<option value="ac">Dave</option>
</select>
And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?
You should use
$('#dropdownid').val('selectedvalue');
Here's an example:
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3 is the index of the option you want.
Live Demo
$('#mySelect').val('fg');...........
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can use this jQuery code which I find it eaiser to use:
$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="your_id" name="name" class="form-control input-md">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
<option value="3">Option #3</option>
<option value="4">Option #4</option>
<option value="5">Option #5</option>
<option value="6">Option #6</option>
<option value="7">Option #7</option>
</select>
You can simply use:
$('#select_id').val('fg')
In your case $("#mySelect").val("fg") :)
May be too late to answer, but at least some one will get help.
You can try two options:
This is the result when you want to assign based on index value, where '0' is Index.
$('#mySelect').prop('selectedIndex', 0);
don't use 'attr' since it is deprecated with latest jquery.
When you want to select based on option value then choose this :
$('#mySelect').val('fg');
where 'fg' is the option value
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
This code worked for me:
$(function() {
$('[id=mycolors] option').filter(function() {
return ($(this).text() == 'Green'); //To select Green
}).prop('selected', true);
});
With this HTML select list:
<select id="mycolors">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.
The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.
So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:
$('#project-locationSearch-dist-input').val('1');
<label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
<select id="project-locationSearch-dist" data-tabindex="1">
<option id="optDistrictOne" value="01">1</option>
<option id="optDistrictTwo" value="02">2</option>
<option id="optDistrictThree" value="03">3</option>
<option id="optDistrictFour" value="04">4</option>
<option id="optDistrictFive" value="05">5</option>
<option id="optDistrictSix" value="06">6</option>
<option id="optDistrictSeven" value="07">7</option>
<option id="optDistrictEight" value="08">8</option>
<option id="optDistrictNine" value="09">9</option>
<option id="optDistrictTen" value="10">10</option>
<option id="optDistrictEleven" value="11">11</option>
<option id="optDistrictTwelve" value="12">12</option>
</select>
Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:
//SPN
spnDDL.combobox({
select: function (event, ui) {
var spnVal = spnDDL.val();
//fire search event
$('#project-locationSearch-pid-input').val('');
$('#project-locationSearch-pid-input').prop('disabled', true);
pidDDL.empty(); //empty the pid list
}
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();
//PID
pidDDL.combobox({
select: function (event, ui) {
var pidVal = pidDDL.val();
//fire search event
$('#project-locationSearch-spn-input').val('');
$('#project-locationSearch-spn-input').prop('disabled', true);
spnDDL.empty(); //empty the spn list
}
});
Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.
Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)
The only other thing to note, much in addition to the post, is:
/*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked. Thus, it's created at that point in time
and its value must be picked fresh. Can't be put into a var and re-used
like the drop down list part of the UI control. So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL); But you can't
do this with the input part of the control. Winded explanation, yes. That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :)
*/
//district
$('#project-locationSearch-dist').combobox({
select: function (event, ui) {
//enable spn and pid drop downs
$('#project-locationSearch-pid-input').prop('disabled', false);
$('#project-locationSearch-spn-input').prop('disabled', false);
//clear them of old values
pidDDL.empty();
spnDDL.empty();
//get new values
GetSPNsByDistrict(districtDDL.val());
GetPIDsByDistrict(districtDDL.val());
}
});
All shared because it took too long to learn these things on the fly. Hope this is helpful.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
$('select#myselect option[value="ab"]')
either can be used to get the selected option value
$('#dropdownID').on('change', function () {
var dropdownselected=$("#dropdownID option:selected").val();
});
or
$('#dropdownID').on('change', function () {
var dropdownselected=this.selectedOptions[0].value;
});

Categories

Resources