Hide an option element if a matching value is selected - javascript

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>

Related

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>

Checking if all selects are completed in Jquery

I am trying to count the number of VISIBLE selects (Which I've done in the alert in the Jquery) and also count the number of VISIBLE selects that have an option selected. If both numbers match then do some action.
Currently, when I change the first select and choose an option, it doesn't alert with a value. When I change the next select and choose an option it shows the count is 1 when it is meant to be 2. when I select the third select then it shows 3. However these numbers are all inaccurate. What is the cause of this?
<div id="secondPanelID">
<div class="form-group input-group">
<label for="gestationalAgeInWeeks">Gestational Age : </label>
<div>
<select id="gestationalAgeInWeeks" name="gestationalAgeInWeeks" class="form-control">
<option disabled selected value>SELECT</option>
<option value="0">0</option>
</select>
</div>
</div>
<div class="form-group input-group">
<label>days</label>
<div>
<select name=gestionalDays class="form-control">
<option disabled selected value>SELECT</option>
<option value="0">0 Days</option>
<option value="1">1 Day</option>
</select>
</div>
</div>
</div>
Added listeners to each of the selects
$("select[name=gestationalAgeInWeeks]").change(checkingColourSelectsGeneralData);
$("select[name=gestionalDays]").change(checkingColourSelectsGeneralData);
Jquery
var selectCounterInGeneral = 0;
function checkingColourSelectsGeneralData(){
alert($('#secondPanelID select:visible').length)
$('#secondPanelID select:visible').change(function () {
var o = $(this);
if (!o.hasClass('counted')) {
selectCounterInGeneral++;
o.addClass('counted');
}
alert("number of selects: "+selectCounterInGeneral);
});
}
Just check if all visible selects have value this way:
function countSelected(e) {
var toReturn = true;
$('select:visible').each(function(i) {
if( !$(this).val() ) {
toReturn = false;
};
});
console.log( toReturn );
};
$('select').on('change', countSelected);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option disabled selected value>--choose--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option disabled selected value>--choose--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select style="display: none;">
<option disabled selected value>--choose--</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
Also on JSFiddle.

HTML/JS Hiding Select options based on another selected value

I have the following two select drop-downs, this one for Office location:
<label class="label_select" for="office">Office<span class="required"><font color="red">*</font></span>
</label>
<select class="select" name="office" onchange="divisionSelectHandler(this)" required>
<option selected disabled style="display:none;" value="">Select Office</option>
<optgroup label ="Arizona">
<option value="Glendale">Glendale</option>
<option value="Mesa">Mesa</option>
<option value="AZRemote">Remote</option>
<option value="Tucson">Tucson</option>
<option value="Yuma">Yuma</option>
</optgroup>
<optgroup label="Oregon">
<option value="ORRemote">Remote</option>
<option value="Salem">Salem</option>
</optgroup>
<optgroup label="Utah">
<option value="Orem">Orem</option>
<option value="UTRemote">Remote</option>
<option value="Taylorsville">Taylorsville</option>
<optgroup>
</select>
and this one for Division:
<label class="label_select" for="division">Division<span class="required"><font color="red">*</font></span>
</label>
<select class="select" name="division" id="divisionstd" required>
<option selected disabled style="display:none;" value="">Select Division</option>
<option value="EarlyIntervention">Early Intervention</option>
<option value="Employment_Services">Employment Services</option>
<option value="Family_Services">Family Services</option>
<optgroup label="OMG-Accounting">OMG-Accounting>
<option value="AccountingAP">AP</option>
<option value="AccountingAR">AR</option>
<option value="AccountingGL">GL</option>
</optgroup>
<option value="HR">OMG-HR</option>
<option value="Residential_Services">Residential</option>
</select>
What I am trying to do is hide certain Divisions based on the Office that is selected. For example, if a user selects "Glendale" from the office drop-down, I would like to hide the OMG-Accounting options from the Divisions drop-down. I am just learning JS and have something that hides the whole Divisions drop-down, but how can I hide individual options? JS:
<script>
function hide(){
var division = document.getElementById('divisionstd');
division.style.visibility = 'hidden';
}
function show(){
var division = document.getElementById('divisionstd');
division.style.visibility = 'visible';
}
function divisionSelectHandler(select){
if(select.value == 'Mesa'){
hide();
}}
</script>
Add id or name or class attribute to your optgroup
<optgroup label="OMG-Accounting" name="test54" id="test54">OMG-Accounting>
<option value="AccountingAP">AP</option>
<option value="AccountingAR">AR</option>
<option value="AccountingGL">GL</option>
</optgroup>
JS :
function divisionSelectHandler(select){
if(select.value == 'Glendale'){
var ele = document.getElementById('test54')
ele.style.display = 'none'
}
}
OR
change html like this one.Assign unique lable to each optgroup
e.g. omgaccounting
<optgroup label="omgaccounting">OMG-Accounting>
<option value="AccountingAP">AP</option>
<option value="AccountingAR">AR</option>
<option value="AccountingGL">GL</option>
</optgroup>
JS :
var arrEle = document.querySelectorAll('optgroup[label="omgaccounting"]');;
arrEle[0].style.display = 'none'
You can hide multiple optgroup in this way using class,label or name
$("select[name=office]").on("change", function() {
var getValue = $(this).val();
var targetGroup = $("select[name=division] optgroup[label='OMG-Accounting']");
(getValue=="Glendale") ? targetGroup.hide() : targetGroup.show();
});
working fiddle : https://jsfiddle.net/8et5raex/
$("select[name=division] optgroup[label='OMG-Accounting']");
targets optgroup with label='OMG-Accounting' under selection box with name division
For example, if a user selects "Glendale" from the office drop-down, I would like to hide the OMG-Accounting options from the Divisions drop-down
Try this in your existing code,
function divisionSelectHandler(select){
if(select.value == 'Glendale'){
$('divisionstd optgroup[label="OMG-Accounting"]').hide();
}
}
Select specific option group and hide it, Right now you are hiding entire select element.
Other options
1) Hide by option VALUE
$('divisionstd option[value="Family_Services"]').hide();
2) Hide by option TEXT
$('divisionstd option[text="OMG-HR"]').hide();
3) Hide OptionGroup by label
$('divisionstd optgroup[label="OMG-Accounting"]').hide();

In several selects make selected options uniq

I have question where you need to find pairs of words in Russian and English
<div class="form-group" id="question4">
<label for="q4FirstSelectEN">4</label>
<div class="row">
<div class="col-lg-offset-2 col-lg-2 q4EN">
<select name="firstSelectEn" id="q4FirstSelectEN">
<option disabled selected style="display: none" value=""></option>
<option value="red">red</option>
<option value="green">green</option>
<option value="purple">purple</option>
</select>
<select class="top-buffer" name="secondSelectEn" id="q4SecondSelectEN">
<option disabled selected style="display: none" value=""></option>
<option value="red">red</option>
<option value="green">green</option>
<option value="purple">purple</option>
</select>
<select class="top-buffer" name="secondSelectEn" id="q4ThirdSelectEN">
<option disabled selected style="display: none" value=""></option>
<option value="red">red</option>
<option value="green">green</option>
<option value="purple">purple</option>
</select>
</div>
<div class="col-lg-2 q4RU">
<select name="firstSelectRu" id="q4FirstSelectRu">
<option disabled selected style="display: none" value=""></option>
<option value="red">красный</option>
<option value="green">зелёный</option>
<option value="purple">фиолетовый</option>
</select>
<select class="top-buffer" name="firstSelectRu" id="q4SecondSelectRu">
<option disabled selected style="display: none" value=""></option>
<option value="red">красный</option>
<option value="green">зелёный</option>
<option value="purple">фиолетовый</option>
</select>
<select class="top-buffer" name="firstSelectRu" id="q4ThirdSelectRU">
<option disabled selected style="display: none" value=""></option>
<option value="red">красный</option>
<option value="green">зелёный</option>
<option value="purple">фиолетовый</option>
</select>
</div>
</div>
</div>
When user selects for example 'red' in (select) inside (div class='q4EN') in all remaining selects in this (div class=q4EN) selected 'red' option become nonSelectable
(nonSelectable is class in css with display:none)
When user change decision and select 'green' instead of 'red' in first (select) red became available in rest selects and green become nonSelectable
When all 3 select have their value user can't change anything
My js for this is not working and I out of ideas
$(".q4EN").find("select").change(function () {
$(".q4EN").find("select")
.not(this)
.find("option:selected")
.addClass("nonSelectable");
});
I believe the problem is order of operations.
$(".q4EN").find("select").change(function () {
$(".q4EN").find("select") //Finds all select lists
.not(this) //Finds all except the one just changed
.find("option:selected") //Finds selected of all except the one just changed
.addClass("nonSelectable"); //Wont do anything because nothing was selected
});
Try the following:
$(".q4EN").find("select").change(function() {UpdateOptions();});
function UpdateOptions(){
var ss = $(".q4EN").find("select");
ss.find('option').prop("disabled", false); //Enable all before disabling selected
ss.each(function () {
var s = $(this).val();
if(s != undefined && s != "") {
ss.find("option[value=" + s + "]").prop("disabled", true);
}
});
}
This is an alternate way to achieve what you need. It basically iterate through every select element and find the corresponding option and disables it.
$('select').find("option").addClass("selectable");
$('select').on("change",function()
{
// $(this).find("option").prop("disabled",false); // uncomment this if you wish to reset the disabled selection
var $thisId = this.id;
var $selectedOption = $(this).find("option:selected").val();
$('select').each(function()
{
if(this.id !== $thisId)
{
// $(this).find("option").removeClass("non-selectable").addClass("selectable"); // uncomment this if you wish to reset the disabled selection
$(this).find("option[value=" + $selectedOption + "]").prop("disabled",true).addClass("non-selectable").removeClass("selectable");
}
});
})
https://fiddle.jshell.net/a2n234eq/4/
To target a specific group ( like EN and RU ) , change $('select') to $('.q4EN select')

Can't get jquery to set value of select input when value of first select changes

I'm trying to update the value of a select input when I change the value of another select input. I cannot get anything to happen on the page and want to make sure I don't have a syntax error or some other dumb thing in this code.
<div class="group">
<div class="inputs types">
<strong style="font-size:13px;">Category:</strong>
<select name="id" id="ctlJob">
<option value="1">Automotive</option>
<option value="2">Business 2 Business</option>
<option value="3">Computers</option>
<option value="4">Education</option>
<option value="5">Entertainment & The Arts</option>
<option value="6">Food & Dining</option>
<option value="7">Government & Community</option>
<option value="8">Health & Beauty</option>
<option value="9">Home & Garden</option>
<option value="10">Legal & Financial Services</option>
<option value="11">Professional Services</option>
<option value="12">Real Estate</option>
<option value="13">Recreation & Sports</option>
<option value="14">Retail Shopping</option>
<option value="15">Travel & Lodging</option>
</select>
<select name="type" id="ctlPerson"></select>
</div>
</div>
<script>
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
$('#ctlPerson').html('<option value="123">ascd</option>');
});
});
</script>
Try using append instead:
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
var ctl = $('#ctlPerson').append('<option value="123">'+val+'</option>')[0].options;
ctl.selectedIndex = ctl.length-1;
});
});
http://jsfiddle.net/J69q8/
I think you also need to set the 'selected' property. Add
$('#ctlPerson option[value="123"]').attr('selected', 'selected');
to the end of the script. You are currently adding the option to the select list, but are not changing the select list to show it.
<div id="test">
<select name="sel" id="sel">
<option name="1" id="1" value="1">Automotive</option>
<option name="2" id="1 value="2">Business 2 Business</option>
<option name="3" id="1 value="3">Computers</option>
</select>
<select name="sel2" id="sel2"></select>
</div>
<script>
$("#sel").change(function() {
var val = $(this).val();
$('#sel2').html('<option value="1">NEW</option>');
)};
</script>
this works fine for what you need to do.
it's something like what you have

Categories

Resources