not allow select same value with two dropdown - javascript

I want to prevent the user from selecting the same value twice in this form
<select name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<option> Applied Information and Communication Technology</option>
<option> Arabic</option>
<option> Art and Design</option>
<option> Biology</option>
<option> Business Studies</option>
</select>
<select name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<option> Applied Information and Communication Technology</option>
<option> Arabic</option>
<option> Art and Design</option>
<option> Biology</option>
<option> Business Studies</option>
</select>

I'm not sure how you're selecting the elements, so I'll give them an ID for simplicity.
Example: http://jsfiddle.net/x4E5Q/1/
function preventDupes( select, index ) {
var options = select.options,
len = options.length;
while( len-- ) {
options[ len ].disabled = false;
}
select.options[ index ].disabled = true;
if( index === select.selectedIndex ) {
alert('You\'ve already selected the item "' + select.options[index].text + '".\n\nPlease choose another.');
this.selectedIndex = 0;
}
}
var select1 = select = document.getElementById( 'select1' );
var select2 = select = document.getElementById( 'select2' );
select1.onchange = function() {
preventDupes.call(this, select2, this.selectedIndex );
};
select2.onchange = function() {
preventDupes.call(this, select1, this.selectedIndex );
};
html
<select id="select1" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<!-- ...and so on... -->
<select id="select2" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option> Accounting</option>
<option> Afrikaans</option>
<!-- ...and so on... -->
EDIT: Changed to deal with browsers that don't support .disabled. Credit to #Zoidberg.

Ultimately, if you can afford the real-estate i would use Radio buttons instead, or checkboxes and only allow them to select 2 check boxes at the most. To me drop downs don't work in this situation
However, if you don't have the real-estate and you must use dropdowns, then your best bet, is once they have selected a value in the first drop down, disable or remove it in the second dropdown, and vice versa (incase they select a value in the first one). I would recommend disabling as opposed to removing, as it will be more apparent to the user what is going on.
<select id="subject1" onchange="updateSelect(this,'subject2');" name="indication_subject[]">
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>
<select id="subject2" name="indication_subject[]" onchange="updateSelect(this,'subject1');" >
<option value="" selected="selected">a </option>
<option value="1"> Accounting</option>
<option value="2"> Afrikaans</option>
<option value="3"> Applied Information and Communication Technology</option>
<option value="4"> Arabic</option>
<option value="5"> Art and Design</option>
<option value="6"> Biology</option>
<option value="7"> Business Studies</option>
</select>
Then the js that goes with it
function updateSelect(changedSelect, selectId) {
var otherSelect = document.getElementById(selectId);
for (var i = 0; i < otherSelect.options.length; ++i) {
otherSelect.options[i].disabled = false;
}
if (changedSelect.selectedIndex == 0) {
return;
}
otherSelect.options[changedSelect.selectedIndex].disabled = true;
}
The only problem is, IE 7 and earlier doesn't support disabled. If this is a deal breaker than you will have to go with removing the option from the Other Select, and then replace it later. Only issue with this is that it will change the order of options, unless you refresh the whole list. To refresh the whole list, you will need to store the options and values in an array (kinda like a model) that never changes and is used to update the selects when the change event occurs.

try this, add id="indication_subject1" in select 1.
and id="indication_subject2" in select 2.
Javascript:
$('#indication_subject1').change(function(){
var indication_subject1 = $('#indication_subject1').val();
var indication_subject2 = $('#indication_subject2').val();
if (indication_subject1 == indication_subject1)
{
$('#indication_subject2').prop('selectedIndex',0);// val = "" selected, or you can add alert('Can't select same value!')
}
});
$('#indication_subject2').change(function(){
var indication_subject1 = $('#indication_subject1').val();
var indication_subject2 = $('#indication_subject2').val();
if (indication_subject2 == indication_subject1)
{
$('#indication_subject1').prop('selectedIndex',0);
}
});

Related

Hide an option element if a matching value is selected

One day I had a problem with PHP and a super guy resolved my problem, this time I learn JavaScript, and I'm really stuck on a project.
Here is the fiddle: https://jsfiddle.net/xasal/8c0kdqm4/5/
As you see, I have 2 selectors, on the left, the user see his characters, at the right, he can chose to switch his "race", the problem is I want JavaScript to run something when the guy selects his character at the left to compare with the right one and automatically delete the option if it's for the same race.. I made the functions for all to disappear, the only problem is the compare value... and when I think my code is nice I have issues in the dev console of unexpected end or syntax
Uncaught SyntaxError: Unexpected end of input
Sorry if it's kinda easy for you I'm really new :x
<select id="charSelect" name="charSelection">
<option value="Knight" selected="selected"><span id="charName">Gooffy</span> - <span class="charJob" onclick="detectChanges()">Knight</span> - lv.<span id="charLvl">175</span></option>
<option value="NightShadow"><span>Soul</span> - <span class="charJob" onclick="detectChanges()">NightShadow</span> - lv.<span>175</span></option>
<option value="Rogue"><span>Veli</span> - <span class="charJob" onclick="detectChanges()">Rogue</span> - lv.<span>175</span></option>
</select>
</section>
<input type="submit" value="Change my class to">
<section class="rightSelect">
<select class="jobSelect" name="jobSelection">
<option value="titan" id="titan" class="charJobChange" selected="selected">Titan</option>
<option value="knight" id="knight" class="charJobChange">Knight</option>
<option value="healer" id="healer" class="charJobChange">Healer</option>
<option value="mage" id="mage" class="charJobChange">Mage</option>
<option value="rogue" id="rogue" class="charJobChange">Rogue</option>
<option value="sorcerer" id="sorcerer" class="charJobChange">Sorcerer</option>
<option value="nightshadow" id="nightshadow" class="charJobChange">NightShadow</option>
</select>
function removeNS() { // example with Hide NS = nightshadow
$('#nightshadow').hide();
console.log("loaded");
}
function selectedCh(){
if($("#leftSelect select").find("option:selected").val() == "NightShadow") {
removeNS();
}
selectedCh();
Try this instead.
I called the function in onchange="selectedCh()" of left select box.
function selectedCh(){
// to get selected option in left select box in lowercase
var selectedtitem = $(".leftSelect select").find("option:selected").val().toLowerCase();
// to get total number of options in right select box
var oplen = $(".rightSelect select option").length;
// enable all option in right select box
$(".rightSelect select option").show();
// Loop for checking the selected option equals to any option in right select box
for(i=1;i<=oplen;i++){
if($(".rightSelect select option:nth-child("+i+")").val() == selectedtitem){
// to hide if equals in right select box option
$(".rightSelect select option:nth-child("+i+")").hide();
}
}
}
// to check first run the code
selectedCh();
Working demo
function selectedCh(){
var selectedtitem = $(".leftSelect select").find("option:selected").val().toLowerCase();
var oplen = $(".rightSelect select option").length;
$(".rightSelect select option").show();
for(i=1;i<=oplen;i++){
if($(".rightSelect select option:nth-child("+i+")").val() == selectedtitem){
$(".rightSelect select option:nth-child("+i+")").hide();
}
}
}
selectedCh();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="leftSelect">
<select id="charSelect" name="charSelection" onchange="selectedCh()">
<option value="Knight" selected="selected"><span id="charName">Gooffy</span> - <span class="charJob" onclick="detectChanges()">Knight</span> - lv.<span id="charLvl">175</span></option>
<option value="NightShadow"><span>Soul</span> - <span class="charJob">NightShadow</span> - lv.<span>175</span></option>
<option value="Rogue"><span>Veli</span> - <span class="charJob" >Rogue</span> - lv.<span>175</span></option>
</select>
</section>
<section class="rightSelect">
<select class="jobSelect" name="jobSelection">
<option value="titan" id="titan" class="charJobChange" selected="selected">Titan</option>
<option value="knight" id="knight" class="charJobChange">Knight</option>
<option value="healer" id="healer" class="charJobChange">Healer</option>
<option value="mage" id="mage" class="charJobChange">Mage</option>
<option value="rogue" id="rogue" class="charJobChange">Rogue</option>
<option value="sorcerer" id="sorcerer" class="charJobChange">Sorcerer</option>
<option value="nightshadow" id="nightshadow" class="charJobChange">NightShadow</option>
</select>
</section>
Hide option if value == 'option 3'
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="selectName">
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3 (hide on chnage)</option>
<option value="option 4">Option 4</option>
<option value="option 5">Option 5</option>
</select>
<script>
$('#selectName').on('change', function () {
if ($(this).val() == 'option 3') {
$('option[value="option 3"]',this).hide();
} else {
$('option[value="option 3"]',this).show();
}
}).trigger('change');;
</script>
Just use a query selector for find the matching option and hide it. Here is a minimal example:
var charSelect = document.querySelector('select[name="charSelection"]');
var jobSelect = document.querySelector('select[name="jobSelection"]');
charSelect.addEventListener('change', function(){
// Unhide any hidden options
jobSelect.querySelectorAll('option').forEach(opt=>opt.style.display = null);
// Hide the option that matches the above selected one
var value = this.value.toLowerCase();
jobSelect.querySelector(`option[value="${value}"]`).style.display = "none";
});
<select name="charSelection">
<option value="Knight" selected="selected">Knight</option>
<option value="NightShadow">NightShadow</option>
<option value="Rogue">Rogue</option>
</select>
<select name="jobSelection">
<option value="titan" selected="selected">Titan</option>
<option value="knight">Knight</option>
<option value="healer">Healer</option>
<option value="mage">Mage</option>
<option value="rogue">Rogue</option>
<option value="sorcerer">Sorcerer</option>
<option value="nightshadow">NightShadow</option>
</select>

How can I set the default value for an HTML <select> element with JavaScript?

How to set the 'selected' (default) value for an HTML <select> element with JavaScript. Aka. currently option0 is 'selected', how to run a script to change it to display the value i want?
this for example because that value is previously saved in a database, and i only want it updated if the user actually specifies to do so. But if i don't specify the value (by re-selecting the previous option), saving the 'edit' will overwrite the previous value with the 'default selected' value the <select> is loaded with.
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
NOTE: Because i lack reputation to add my answer (below) to the general thread on this topic, here the solution i got to using javascript, to set an option to be the option displayed/selected in the selector. This can also be a <%= value %> from a database.
Use value property to set new selected value using JavaScript
document.getElementById('selector').value="2";
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
<script>
let options = document.getElementsByTagName('option');
for(i=0; i<options.length; i++){
if (options[i].value === "<%= or_some_string %>"){
options[i].selected = true;
}
}
</script>
We get all the options (this is an html collection) and iterate over it to check if any option is equal to the "String" or "<%=string_value_from_database%>". And set it's .selected to true.
NOTE - MAYBE BETTER - DEFFO SHORTER: with help in the comments:
<script>
let to_select = document.getElementById('selector');
to_select.value = "<%= value %>";
</script>
Where to_select.value is either set to the value you want, or to a database value. Do note, you may or may not need the ".." around the value you set, depending on the setup of the <select> and how you stored your data.
use this
document.getElementById("selector").selectedIndex = 3;
original

Get data-* attribute of the selected <option>

I'm trying to get the second value of an option tag using document.get.elementbyId.
<select id="test" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-doj="20-06-2011">John</option>
<option value="2" data-doj="10-05-2015">Clif</option>
<option value="3" data-doj="01-01-2008">Alexander</option>
</select>
Usually, I would use document.getElementById("test").value; to get the value of one option. What should I do if I have multiple values like in this case? document.getElementById("test").data-doj;?
Thank you.
Use HTMLSelectElement.selectedIndex
The HTMLSelectElement.selectedIndex is a long that reflects the index of the first or last selected element, depending on the value of multiple. The value -1 indicates that no element is selected.
To access data-* attributes, use dataset
Note - this in event-handler refers to the element on an event is invoked.
let select = document.getElementById("test");
select.onchange = function() {
let selectedI = this.selectedIndex;
console.log(this.options[selectedI].dataset.doj)
};
<select id="test" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-doj="20-06-2011">John</option>
<option value="2" data-doj="10-05-2015">Clif</option>
<option value="3" data-doj="01-01-2008">Alexander</option>
</select>
Like this
navigate using selectedIndex
document.getElementById("test").addEventListener("change",function() {
const opt = this.options[this.selectedIndex];
console.log(opt.value,
opt.getAttribute("data-doj"), // or opt.dataset.doj
opt.text)
})
<select id="test" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-doj="20-06-2011">John</option>
<option value="2" data-doj="10-05-2015">Clif</option>
<option value="3" data-doj="01-01-2008">Alexander</option>
</select>
Strangely, no one still suggested.
There's a way to access HTMLCollection of the selected options with HTMLSelecteElement.selectedOptions. If you have only one <option> selected at a time, you may simply pull its first element (with [0]).
To access data-* attribute there's a proper API, which implies .dataset['propertyname'] kind of syntax:
document.getElementById('test').addEventListener('change', function(){
const [selectedOption] = this.selectedOptions,
dataDoj = selectedOption.dataset.doj
console.log(dataDoj)
})
<select id="test" class="form-control">
<option value="">-- Select --</option>
<option value="1" data-doj="20-06-2011">John</option>
<option value="2" data-doj="10-05-2015">Clif</option>
<option value="3" data-doj="01-01-2008">Alexander</option>
</select>
Please see the working example below, How you can get value, text and custom attribute of selected option -
function trackValue(){
var element = document.getElementById("test");
var option_value = element.options[element.selectedIndex].value;
var option_text = element.options[element.selectedIndex].text;
var option_doj = element.options[element.selectedIndex].getAttribute('data-doj')
console.log('value-', option_value);
console.log('text-', option_text);
console.log('doj-', option_doj);
}
<select id="test" class="form-control" onChange="trackValue();">
<option value="">-- Select --</option>
<option value="1" data-doj="20-06-2011">John</option>
<option value="2" data-doj="10-05-2015">Clif</option>
<option value="3" data-doj="01-01-2008">Alexander</option>
</select>

Populate a select with options selected from various selects - jquery

I´m not expert with javascript & jquery, and I just googled for many days but can´t find the answer.
How can I populate a select with options selected from other selects. For this example from the 1st select I choose Manchester, from 2nd I choose Bogota and the 3rd must be populated with Manchester and Bogota:
Select One <br>
<select id="city" name="city">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="2">Paris</option>
<option value="3">Madrid</option>
</select><br>
Select 2 <br>
<select id="city2" name="city2">
<option value="0"></option>
<option value="4">Bogota</option>
<option value="5">Buenos Aires</option>
<option value="6">Quito</option>
</select><br>
Select 3, populated whit the options of the previous 2 selects <br>
<select id="street" name="street">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="4">Bogota</option>
</select>
Many thanks for help me.
The following jQuery will refresh the street select list any time a change is made to a select with class refresh on it.
function refreshList() {
$('#street option').remove(); //Clear the dropdown
$('#street').append('<option value="0"></option>'); //Add the blank option
$('.refresh').each(function() { //Loop through every instance of class 'refresh'
var v = $(this).val(); //Selected Value
var t = $(this).find('option[value="' + v + '"]').text(); //Selected Text
if (v != 0) { //If value isn't blank, add option to Street
$("#street").append('<option value="' + v + '">' + t + '</option>');
}
});
}
$(document).ready(function() { //When the page loads
$('.refresh').change(function() { //Initialize a click-event listener for class 'refresh'
refreshList(); //Run above function
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select One <br>
<select id="city" name="city" class="refresh">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="2">Paris</option>
<option value="3">Madrid</option>
</select><br>
Select 2 <br>
<select id="city2" name="city2" class="refresh">
<option value="0"></option>
<option value="4">Bogota</option>
<option value="5">Buenos Aires</option>
<option value="6">Quito</option>
</select><br>
Select 3, populated with the options of the previous 2 selects <br>
<select id="street" name="street">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="4">Bogota</option>
</select>
$('select#city').change(function() {
var $selected = $('option:selected', this).clone()//make a copy of selected option
$('#street').append($selected)//put the selected option in the 3rd select
})
$('select#city2').change(function() {
var $selected = $('option:selected', this).clone();//make a copy of selected option
$('#street').append($selected)//put the selected option in the 3rd select
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Select One
<br>
<select id="city" name="city">
<option value="0"></option>
<option value="1">Manchester</option>
<option value="2">Paris</option>
<option value="3">Madrid</option>
</select>
<br>Select 2
<br>
<select id="city2" name="city2">
<option value="0"></option>
<option value="4">Bogota</option>
<option value="5">Buenos Aires</option>
<option value="6">Quito</option>
</select>
<br>Select 3, populated whit the options of the previous 2 selects
<br>
<select id="street" name="street">
<option value="0"></option>
</select>
Use .clone() to make a copy of selected option
Description: Create a deep copy of the set of matched elements.
Then use .append() to insert the cloned element to 3rd select
Description: Insert content, specified by the parameter, to the end of each element in the set of matched elements.

Multiple identical <select> tags where each option can be selected once

I am creating a website where their are 4 identical dropdown menu's, each dropdown menu has got 10 options. But each of those options can only be selected in one of the dropdown menu's.
So for example:
When I select option 1 in this dropdown menu.
<select name="select1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I can't select it in this one. So it should say disabled in option one.
<select name="select2">
<option value="1" //disabled >1</option>
<option value="2">2</option>
<option value="3">2</option>
<option value="4">4</option>
</select>
I don't know how to do it myself so I would be very glad if someone could help me.
To provide a better user experience, you should disable the items using JavaScript when the user selects something in a drop down. Are you using jQuery by any chance?
You should also enforce it on the server because as a general rule, clients are not to be trusted.
If I understand you correctly, what you are trying to achieve is better done via checkboxes.
Instead of <select> do this:
<input type="checkbox" name="1" value="1">option1<br>
<input type="checkbox" name="2" value="2">option2 <br> ...
The code below does what you are asking. I also made a jsfiddle
It will correctly disable and enable options as options from ANY of the select inputs are changed.
The javascript
<script type="text/javascript">
// *** EDIT THIS ***
var selectIds = new Array('select1', 'select2', 'select3', 'select4'); // all of the select input id values to apply the only one option value anywhere rule against
function process_selection(theObj){
var allSelectedValues = new Array(); // used to store all currently selected values
// == get all of the currently selected values for all the select inputs
for (var x=0; x<selectIds.length; x++){
var v = document.getElementById(selectIds[x]).value; // the value of the selected option for the select input currently being looked at in the loop (selectIds[x])
// if the selected option value is not an empty string ..
if(v!==""){
// store the value of the selected option and it's associated select input id value
allSelectedValues[v] = selectIds[x];
}
}
// == now work on each option within each select input
for (var x=0; x<selectIds.length; x++){
// loop thru all the options of this select input
var optionObj = document.getElementById(selectIds[x]).getElementsByTagName("option");
for (var i = 0; i < optionObj.length; i++) {
var v = optionObj[i].value; // the value of the current option in the iteration
// only worry about option values that are not an empty string ("")
if(v!==""){
if(allSelectedValues[v]){
if(allSelectedValues[v] && allSelectedValues[v] != selectIds[x]){
// disable this option because it is already selected
// and this select input is NOT the one that it is selected in
optionObj[i].disabled = true;
}
}else{
// enable this option because it is not already selected
// in any of the other select inputs
optionObj[i].disabled = false;
}
}
} // end for (option loop)
} // end for (select loop)
} // end func
</script>
The HTML that works with the above
But really the code above will work with any select inputs on your page by editing the one line indicated in the js code above
<select name="select1" id="select1" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<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>
</select>
<select name="select2" id="select2" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<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>
</select>
<select name="select3" id="select3" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<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>
</select>
<select name="select4" id="select4" onchange="process_selection(this)">
<option value="">-- choose one --</option>
<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>
</select>
As others have mentioned, it is a cleaner way to do it in checkboxes. However, just to improve my JavaScript skills, I came up with something that should answer what you asked for:
var boxes, i, disableOthers;
boxes = document.getElementsByTagName('select');
disableOthers = function () {
'use strict';
var i, j, k, selectedValues = [],
options;
for (i = 0; i < boxes.length; i += 1) {
selectedValues.push(boxes[i].value);
for (j = 0; j < boxes.length; j += 1) {
if (boxes[j] !== boxes[i]) {
options = boxes[j].querySelectorAll('option');
for (k = 0; k < options.length; k += 1) {
options[k].disabled = (selectedValues.indexOf(options[k].value) > -1);
}
}
}
}
};
for (i = 0; i < boxes.length; i += 1) {
boxes[i].addEventListener('change', disableOthers, false);
}
See jsFiddle

Categories

Resources