Two HTML selects with differing selected values - javascript

I got following HTML code:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
So both of them have same data. I need to secure, that user can't select same value in both of them.
I hoped, that JQuery has some nice feature like:
$("#first").getOptions()
or even
$("#first").setOptions()
but unfortunately, it doesn't. This makes it very complicated for me, because I don't know JQuery very well ...
So, what is the best approach to solve my problem?

You can get the value of the currently selected option by doing:
$('#first option:selected').text();
$('#second option:selected').text();
Assuming I understand your question, you don't want the user to be able to enter the same value in each box. So, something similar to:
$first = $('#first');
$second = $('#second');
$first.on('change', function() {
$second.find('option').attr('disabled', false);
var firstVal = $first.find('option:selected').text();
$second.find('option:contains("'+ firstVal +'")').attr('disabled', true);
});
$second.on('change', function() {
$first.find('option').attr('disabled', false);
var secondVal = $second.find('option:selected').text();
$first.find('option:contains("'+ secondVal +'")').attr('disabled', true);
});
I should probably note that there are ways for you to achieve your getOptions() and setOptions() ideas, you can do $select.find('option') to get the options. For setting them, define some options in html and set the select element's innerHTML to those elements:
var options = '<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>';
$select.html(options);
JSFiddle demo

You can disable single options in your select
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2" disabled>Two</option>
<option value="3">Three</option>
</select>
Handle event onSelect on first select and based on it disable proper <option> in second select

When one is changed, if the other is the same, you could change it back to default, like this.
$(document).on('change', '#first', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#second').val(0);
}
});
$(document).on('change', '#second', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#first').val(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

Try this(codepen):
HTML:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Javascript/jQuery:
var strUser;
var strUser2;
$(function() {
$("#first").change(function() {
var e = document.getElementById("first");
strUser = e.options[e.selectedIndex].text;
if (strUser == strUser2) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("first").disabled=true;
} else {
document.getElementById("second").disabled=false;
}
});
});
$(function() {
$("#second").change(function() {
var e = document.getElementById("second");
strUser2 = e.options[e.selectedIndex].text;
if (strUser2 == strUser) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("second").disabled=true;
} else {
document.getElementById("first").disabled=false;
}
});
});
Essentially, this code will retrieve selected values from the dropdowns on change, and then a comparison will be made. If the values are equal, the recently selected dropdown will be disabled. You then will have to select a different value in the other dropdown to re-enable the disabled dropdown. Here's the codepen that displays the working functionality. This will not allow a user to select two of the same values without a dropdown being disable and turned off.

Related

Javascript - disabling options on change to prevent duplicate selections in select dropdowns causing issues with .val()

I have a set of 3 select dropdowns. I want the user to only be able to select 1 unique option across each of these 3 dropdowns. To do this I am getting the value on change of any of the select dropdowns and then disabling that option across all of the select boxes. This is working fine here:
$('.select-cont select').change(function() {
var selection = $(this).val();
$('select option[value="' + selection + '"]').attr('disabled',true);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select-cont">
<label>Select 1</label>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<label>Select 2</label>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<label>Select 3</label>
<select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
</div>
However, I also want the user to be able to change their selection, and if they do, the previous option they had selected should no longer be disabled. For that, I am getting the current option on click of the select so that I can target it to remove the disabled attribute:
var prevSelection;
$('.select-cont select').click(function() {
// $(this).val(); doesn't work for some reason
console.log($(this).val());
// event.target.value does work so let's use that
prevSelection = event.target.value;
}).change(function() {
var selection = $(this).val();
$('select option[value="' + prevSelection + '"]').attr('disabled',false);
$('select option[value="' + selection + '"]').attr('disabled',true);
});
$('button').click(function() {
// this returns null if the click/change function exists
console.log($('#first').val());
});
button {
margin-top:3rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select-cont">
<label>Select 1</label>
<select id="first">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<label>Select 2</label>
<select id="second">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
<label>Select 3</label>
<select id="third">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
</div>
<button>Click to log first selection</button>
This is presenting two issues, both seem to have to do with .val() The first issue is that if I try to log $(this).val() within the click function, it returns null. If I instead use event.target.value then it correctly returns my previously selected option.
The other issue is that when I later try to get the values from the select boxes(on button click in the example) using $(element).val() also returns null. But if I remove the click/change function, then .val() correctly returns the selected value when I click the button. Any idea what's going on here?

javascript - Hide Options from Multiple Selection Box when an option from another select is selected

I need your help. So what I want to do is when a user select an option from one select, automatically hide an option from another multiple select.
Example:
if a user choose Car from select A, I want the car option from the select B to be automatically removed or hidden.
select A:
<select name="my_option_one" required id="id_my_option_one">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
Select B:
<select name="my_option_two" id="id_my_option_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
This is what I have tried but none of it worked.
$(document).ready(function() {
$("#id_my_option_one").change(function() {
if ($(this).val() === 'C') {
$("#id_my_option_two option[value='C']").options[0].remove();
$('select[name=my_option_two] option:eq(1)').hide();
$("#id_my_option_two option[value=" + 'C' + "]").hide();
$("#id_my_option_two option[value='C']").attr('disabled','disabled').hide();
}
});
});
function my_optionsChange() {
$("#id_my_options_two option").show(); //.css("display", "block");
$("#id_my_options_two option[value='" + $("#id_my_options").val() + "']").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select name="my_options" required id="id_my_options" onchange="my_optionsChange()">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
I made an example which is longer because it's split into parts so you understand better what is going on.
I tried to name the variables so that it's clear what they are, but if you have any questions, please ask in the comments.
Let me know if this works for you.
const firstSelect = $('#id_my_options')
const secondSelect = $('#id_my_options_two')
firstSelect.on('change',function() {
const selected = $(this).find('option:selected');
const selectedValue = selected.val()
const secondOptions = secondSelect.children();
secondOptions.each(function() {
const secondValue = $(this).val()
secondValue === selectedValue ? $(this).hide() : $(this).show()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="my_options" required id="id_my_options">
<option value="Choose" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options" id="firstblock" onchange="disable(2,this.value);">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options" id="secondblock" onchange="disable(1,this.value);">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<script>
function disable(needtoblock,val){
console.log(needtoblock+" "+val);
if(val != ""){
if(needtoblock == 1){
$("#firstblock option[value='"+val+"']").prop('disabled', true);
}else if(needtoblock == 2){
$("#secondblock option[value='"+val+"']").prop('disabled', true);
}else{
}
}else{
$("#secondblock option").prop('disabled', false);
$("#firstblock option").prop('disabled', false);
}
}
</script>
This is how code could look, definetly you need to update and make it suitable for you.
I know, this is a bit late, but maybe it is of interest to someone out there. I understood the demand of OP so, that the hiding of options was to be done in any direction, or potentially spanning over multiple selector boxes. The following script will do exactly that: if you select an option in one selector it will go through the other selectors of the defined group $grp (by doing $grp.not(this).each((i,trg)=> ...)) and will hide/show all options there, depending of whether thay have been selected elsewhere already.
The $(to).toggle(...) method sets the visibility of each option (to) within trg, based on the existence of selected options with the same value in the sibling selectors of trg (again, limited to the current group $grp).
Maybe the script is a little too condensed for easy reading but it shows how much you can achieve with very little code when you use the power of jQuery.
const $grp=$('select[id^=id_my_options]') // define the selector group
$grp.on('change',function(ev){ // bind the change event ...
$grp.not(this).each((i,trg)=> // work on each sibling-selector (trg) of clicked
// selector (this), but only within jquery
// selection $grp
$('option[value!=""]',trg).each((j,to)=> // for all options of sibling-selectors of
// trg (within jquery selection $grp):
$(to).toggle($grp.not(trg).find('option[value='+to.value+']:selected').length==0))
// toggle the visibiltiy of that option
)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="my_options" required id="id_my_options">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car2</option>
<option value="H">House2</option>
<option value="A">Airplane2</option>
</select>
<select name="my_options_three" id="id_my_options_three" multiple="multiple">
<option value="O">yet another option</option>
<option value="C">Car3</option>
<option value="H">House3</option>
<option value="A">Airplane3</option>
</select>
<br><br>
<select name="my_options_four" id="id_your_options_four" multiple="multiple">
<option value="O">and some unrelated options</option>
<option value="C">Car3</option>
<option value="H">House3</option>
<option value="A">Airplane3</option>
</select>

Change value of select list with value of another select list jquery

How can I change the value of a select list with the value of another select list
<select class="main-filter" id="Test1" name="Test1"><option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Need to replace #ReplaceThisText# with value selected from above select box
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Chnage Value</option>
</select>
I have tried code from this link Change the Text of a Option with jQuery
and jquery how to find and replace a selected option that has a certain value
but cannot seem to get it to work
My code is
$('#Test1').change(function () {
sessionStorage.setItem("Test1", $(this).val());
$('.main-filter :selected:contains("#ReplaceThisText#")').val($(this).val());
location.href = $(this).val();
});
:contains will look at the .text() value - but your #ReplaceThisText# is not in the .text() value - so you'll need to use .filter() to find it instead:
Adding some console.logs so you can see what's happening and updated the .val(newval) code to make the replacement.
$('#Test1').change(function() {
var newval = $(this).val();
console.log("before", $(".main-filter :contains('Change Value')").val())
var opt = $('.main-filter option').filter(function() {
return $(this).val().indexOf("#ReplaceThisText#") >= 0;
});
console.log("opt length", opt.length);
opt.each(function() {
$(this).val($(this).val().replace(/#ReplaceThisText#/gi, newval));
});
console.log("after", $(".main-filter :contains('Change Value')").val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="main-filter" id="Test1" name="Test1">
<option value="">Select Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
<select id="selectfilter" name="selectfilter" class="form-control main-filter">
<option value="">Sort Products</option>
<option value="/?id=na&selectfilter=hl&Type=#ReplaceThisText#">Change Value</option>
</select>

Disable 3th, 4th dropdown list if 1st or 2nr are selected

I have this issue: In my form there are 4 dropdownlist and when the 1st (category1) or 2nd (software1) dropdown list is selected, the 3th (category2) and 4th (software2) must be disabled.
For this issue I find this script at disable-second-dropdown-if-the-first-is-not-selected but I do not trust to modify this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
category1
<select name='cat1'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software1
<select name='soft1'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<br />
category2
<select name='cat2'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software2
<select name='soft2'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<script type="text/javascript">
var setEnabled = function(e) {
var name = this.name.replace(/1/, '2'); //get name for second drop down
$('select[name=' + name + ']')
.prop('disabled', 0 === this.selectedIndex) // disable if selected option is first one
};
$(function() {
$('select[name=cat1], select[name=soft1]')
.on('change', setEnabled)
.trigger('change'); // trigger on page load
});
</script>
How to modify this?
Thanks
I think the main thing you want is to flip === for !==
However, to get this working on a matrix, where both top inputs trigger enabling/disabling of both bottom inputs, you'll need to test both on change of either.
var setEnabled = function(e) {
var selected = $('select[name=cat1]').prop('selectedIndex') > 0 || $('select[name=soft1]').prop('selectedIndex') > 0;
$('select[name=cat2], select[name=soft2]').prop('disabled', selected); // disable if selected option is first one
if (selected) {
$('select[name=cat2], select[name=soft2]').prop('selectedIndex', 0)
}
};
$(function() {
$('select[name=cat1], select[name=soft1]')
.on('change', setEnabled)
.trigger('change'); // trigger on page load
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</script>
category1
<select name='cat1'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software1
<select name='soft1'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>
<br />
category2
<select name='cat2'>
<option value='0'>Select one</option>
<option value='1'>little</option>
<option value='2'>good</option>
</select>
software2
<select name='soft2'>
<option value=''>Select one</option>
<option value='W'>Word</option>
<option value='E'>Excel</option>
<option value='PP'>Power Point</option>
</select>

jQuery remove SELECT options based on another SELECT selected (Need support for all browsers)

Say I have this dropdown:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I want it so that when the user selects 1, this is the thing that the user can choose for dropdown 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
Or if the user selects 2:
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
</select>
Or if the user selects 3:
<select id="theOptions2">
<option value="b">b</option>
<option value="c">c</option>
</select>
I tried the code posted here:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
But it doesn't work for selects.
Please help!
Thank you!
UPDATE:
I really like the answer Paolo Bergantino had on:
jQuery disable SELECT options based on Radio selected (Need support for all browsers)
Is there anyway to modify this to work with selects instead of radio buttons?
jQuery.fn.filterOn = function(radio, values) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(radio).click(function() {
var options = $(select).empty().data('options');
var haystack = values[$(this).attr('id')];
$.each(options, function(i) {
var option = options[i];
if($.inArray(option.value, haystack) !== -1) {
$(select).append(
$('<option>').text(option.text).val(option.value)
);
}
});
});
});
};
This works (tested in Safari 4.0.1, FF 3.0.13):
$(document).ready(function() {
//copy the second select, so we can easily reset it
var selectClone = $('#theOptions2').clone();
$('#theOptions1').change(function() {
var val = parseInt($(this).val());
//reset the second select on each change
$('#theOptions2').html(selectClone.html())
switch(val) {
//if 2 is selected remove C
case 2 : $('#theOptions2').find('option:contains(c)').remove();break;
//if 3 is selected remove A
case 3 : $('#theOptions2').find('option:contains(a)').remove();break;
}
});
});
And the beautiful UI:
<select id="theOptions1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select id="theOptions2">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
You can add classes to your <option>s to store which go with each value of #theOptions1:
<select id="theOptions2">
<option value="a" class="option-1 option-2">a</option>
<option value="b" class="option-1 option-2 option-3">b</option>
<option value="c" class="option-1 option-3">c</option>
</select>
then do this:
$(function() {
var allOptions = $('#theOptions2 option').clone();
$('#theOptions1').change(function() {
var val = $(this).val();
$('#theOptions2').html(allOptions.filter('.option-' + val));
});
});
For the record you can NOT remove options in a select list in Internet Explorer.
try this. this will definitely work
$(document).ready(function () {
var oldValue;
var oldText;
var className = '.ddl';
$(className)
.focus(function () {
oldValue = this.value;
oldText = $(this).find('option:selected').text();
})
.change(function () {
var newSelectedValue = $(this).val();
if (newSelectedValue != "") {
$('.ddl').not(this).find('option[value="' + newSelectedValue + '"]').remove();
}
if ($(className).not(this).find('option[value="' + oldValue + '"]').length == 0) { // NOT EXIST
$(className).not(this).append('<option value=' + oldValue + '>' + oldText + '</option>');
}
$(this).blur();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form action="/Home/Ex2" method="post">
<select class="ddl" id="A1" name="A1">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A2" name="A2">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A3" name="A3">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<select class="ddl" id="A4" name="A4">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
<hr />
<input type="submit" name="submit" value="Save Data" id="btnSubmit" />
</form>
Actually, using the code below will remove a dropdown option just fine in IE, as long as it is not the selected option (it will not work on "a" without deselecting that option first):
var dropDownField = $('#theOptions2');
dropDownField.children('option:contains("b")').remove();
You just run this to remove whatever option you want to remove under a conditional statement with the first group (theOptions1) - that if one of those is selected, you run these lines:
var dropDownField = $('#theOptions2');
if ($('#theOptions1').val() == "2") {
dropDownField.children('option:contains("c")').remove();
}
if ($('#theOptions1').val() == "3") {
$("#theOptions2 :selected").removeAttr("selected");
$('#theOptions2').val('b');
dropDownField.children('option:contains("a")').remove();
}
-Tom

Categories

Resources