JavaScript - Dropdown value dependent - javascript

I have two dropdown right now. I want to when the user selects "NO" the other automatically selects "YES" and vice versa.
I'm assuming I use JS here to make this occur, but not sure where to start. Below is my dropdown html code. If someone could help me get started, it would be helpful.
Code:
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" name="cmicrophone">
<option value=" " selected = "selected"> </option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" name = "microphone">
<option value=" " selected="selected"> </option>
<option value="on" >ON</option>
<option value="off">OFF</option>
</select>
</div

You can assign a same class to each select element and bind change event listener.
$('.elem').on('change', function() {
if ($(this).val() == 'on') {
$('.elem').not(this).val('off');
} else {
$('.elem').not(this).val('on');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class='elem' name="cmicrophone">
<option value="" selected = "selected"></option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class='elem' name="microphone">
<option value="" selected = "selected"></option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>

A good starting point might be listening for changes on one select, and when the change happens, selecting the other <select> and setting the right value

Here's a vanilla JS solution (no jquery required).
The idea here is to:
select both <select> elements and save them into variables to refer to later using document.querySelector
add input event listeners on both elements that call a function to handle the event
then use inside the function selectElement.selectedIndex to check the selected index of one element and use that to set the value of the other.
// select the `<select>` elements
const cmicrophone = document.querySelector('#cmicrophone');
const microphone = document.querySelector('#microphone');
// define function to handler the events
function inputHandler(thisSelect, otherSelect) {
if (thisSelect.selectedIndex == 1) {
otherSelect.selectedIndex = 2;
} else if (thisSelect.selectedIndex == 2) {
otherSelect.selectedIndex = 1;
} else {
thisSelect.selectedIndex = 0;
otherSelect.selectedIndex = 0;
}
}
// add event listeners that will 'fire' when the input of the <select> changes
cmicrophone.addEventListener('input', event => {
inputHandler(cmicrophone, microphone);
});
microphone.addEventListener('input', event => {
inputHandler(microphone, cmicrophone);
});
<div>Currently:
<select id="cmicrophone" name="cmicrophone">
<option value=" " selected = "selected"> </option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div>Microphone:
<select id="microphone" name="microphone">
<option value=" " selected="selected"> </option>
<option value="on" >ON</option>
<option value="off">OFF</option>
</select>
</div>
One more thing to add: You assigned the same value to multiple ids. You should only assign one unique id per element.

Related

How to refresh a select list in html

I have a drop-down list where depending on the selected value, the next drop-down list shows specific values. when changing the value of the first list and then going back to the old value, the second list does not update. keeps the same value selected before. How can I make the second list update to the value I marked as selected by default whenever I change the value of the first list?
I hope you guys were able to understand me, and I thank you for your time.
Here's the code:
<select onchange="showprd('hidevalue', this), showprd2('hidevalue2', this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="hidevalue">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="hidevalue2">
<option value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</body>
<script>
function showprd(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 0 ? 'block' : 'none';
}
function showprd2(id, elementValue) {
document.getElementById(id).style.display = elementValue.value == 1 ? 'block' : 'none';
}
</script>
TL;DR. Control the input value changes in one place.
Please see the updated snippet below. html structure hasn't been changed, but I've removed the inline js call and updated the id names. JavaScript blocks are commented in details.
In a nut-shell, this code listens for any change to the parent select dropdown. Whenever a change occurs, its child dropdowns will reset their values and toggle their visibility accordingly.
// Assign each dom element to a variable
const primarySelect = document.querySelector('#primary');
const childSelect1 = document.querySelector('#child1');
const childSelect2 = document.querySelector('#child2');
const defaultValues = document.querySelectorAll('.default');
function resetInputs() {
// Reset the child select options to default
defaultValues.forEach(option => option.selected = true);
}
function handlePrimary(e) {
// Reset the child select values whenever the parent value changes
resetInputs();
// `input` value is always a string. Here we're converting it to a number
const val = parseFloat(e.target.value);
// Toggle visibility of child select dropdowns
[childSelect1, childSelect2].
forEach((select, i) => select.style.display = val === i ? 'block' : 'none');
}
primarySelect.addEventListener('change', handlePrimary);
<select id="primary">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<br>
<br>
<select hidden id="child1">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="pleno">Pleno</option>
<option value="integrado">Integrado</option>
</select>
<select hidden id="child2">
<option class="default" value="" disabled selected hidden>Selecione o produto</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
If I understood correctly, the expected behavior is when the second or third <select> is hidden, the <select> should go back to default (the first <option>?). If so, then remove disabled and hidden from the first <option> of the second and third <select> then add the following:
selectObj.hidden = true;
selectObj.selectedIndex = 0;
The example below has a <form> wrapped around everything (always use a form if you have more than one form control. By using HTMLFormElement interface I rewrote the code and can reference all form controls with very little code. Inline event handlers are garbage so don't do this:
<select id='sel' onchange="lame(this)">
Instead do this:
selObj.onchange = good;
OR
selObj.addEventListener('change', better)
Read about events and event delegation
const UI = document.forms.UI;
UI.onchange = showSelect;
function showSelect(e) {
const sel = e.target;
const IO = this.elements;
if (sel.id === "A") {
if (sel.value === '0') {
IO.B.hidden = false;
IO.C.hidden = true;
IO.C.selectedIndex = 0;
} else {
IO.B.hidden = true;
IO.B.selectedIndex = 0;
IO.C.hidden = false;
}
}
}
<form id='UI'>
<select id='A'>
<option disabled selected hidden>Pick</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<br>
<br>
<select id="B" hidden>
<option selected>Pick B</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
<select id="C" hidden>
<option selected>Pick C</option>
<option value="0">0</option>
<option value="1">1</option>
</select>
</form>
I give you an example for your reference:
let secondList = [
[{
value: "pleno",
text: "Pleno"
},
{
value: "integrado",
text: "Integrado"
}
],
[
{
value: "junior",
text: "Junior"
},
{
value: "senior",
text: "Senior"
}
]
]
function update(v){
let secondSelectBox=document.getElementById("second");
secondSelectBox.style.display="none";
let optionList=secondList[v.value];
if (optionList){
let defaultOption=new Option("Selecione o produto","");
secondSelectBox.innerHTML="";
secondSelectBox.options.add(defaultOption);
optionList.forEach(o=>{
let vv=new Option(o.text,o.value);
secondSelectBox.options.add(vv);
})
secondSelectBox.style.display="block";
}
}
<select onchange="update(this)">
<option value="" disabled selected hidden>Selecione</option>
<option value="0">São Francisco</option>
<option value="1">Bradesco</option>
</select>
<select hidden id="second">
</select>

Adding event listener to multiple select elements in js

I have different select elements for changing the size of different products, each size has a different price. I can do it with one select element using querySelector but it won't work with querySelectorAll.
Here's my code for changing only one select element:
const price = document.querySelector(".price");
const select = document.querySelector(".select");
select.addEventListener("change", () => {
price.innerText = select.options[select.selectedIndex].value;
});
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$20">40cmx40cm</option>
<option value="$30">30cmx40cm</option>
<option value="$50">50cmx50cm</option>
</select>
</div>
I've tried for loops and forEach but nothing worked (probably cause i'm doing it wrong).
Any help would be appreciated. I'm losing my mind.
You can accomplish this by using "event delegation" where you set up just one handler on an element that is a common ancestor to all the select elements you wish to handle events on. The event will originate at the select but not be handled there and will "bubble" up to the ancestor you choose. Then you handle the event at that ancestor and use the event.target that will be accessible in the handler to reference the actual element that triggered the event and relative DOM references to reference the p element you need to update.
The benefit here is that you only set up one handler (which saves on memory and performance) and the code is simplified. Also, you can add new select structures without having to alter the handling code at all.
// Set up a single handler at a common ancestor of all the select elements
document.body.addEventListener("change", function(event){
// event.target references the element that actually triggered the event
// Check to see if the event was triggered by a DOM element you care to handle
if(event.target.classList.contains("select")){
// Access the <p> element that is the previous sibling to the
// select that triggered the event and update it
event.target.previousElementSibling.textContent = event.target.value
}
});
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$20">40cmx40cm</option>
<option value="$30">30cmx40cm</option>
<option value="$50">50cmx50cm</option>
</select>
</div>
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$20">40cmx40cm</option>
<option value="$30">30cmx40cm</option>
<option value="$50">50cmx50cm</option>
</select>
</div>
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$20">40cmx40cm</option>
<option value="$30">30cmx40cm</option>
<option value="$50">50cmx50cm</option>
</select>
</div>
Try this
const selects = document.querySelectorAll('.selects');
selects.forEach(el => el.addEventListener('click', event => {
//add you code
}));
Simple Solution
You can use this version which works fine.
let price = document.querySelector(".price");
let select = document.getElementsByClassName("select");
let i;
for (i = 0; i < select.length; i++) {
select[i].addEventListener('change', (self) => {
let el = self.target;
let value = el.options[el.selectedIndex].value;
price.innerText = value;
});
}
<div>
<p class="price">$15</p>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$201">40cmx40cm</option>
<option value="$301">30cmx40cm</option>
<option value="$501">50cmx50cm</option>
</select>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$202">40cmx40cm</option>
<option value="$302">30cmx40cm</option>
<option value="$502">50cmx50cm</option>
</select>
<select class="select">
<option disabled hidden selected>size</option>
<option value="$203">40cmx40cm</option>
<option value="$303">30cmx40cm</option>
<option value="$503">50cmx50cm</option>
</select>
</div>
I think you can do the following thing:
selects = document.querySelectorAll(".select");
prices = document.querySelectorAll(".price");
for(let index = 0; index < selects.length; index+=1){
selects[index].addEventListener("change", () => {
prices[index].innerText = selects[index].options[selects[index].selectedIndex].value;
});
}

Multiple drop down boxes?

I'm trying to get multiple drop down boxes to open when selecting different prompts from an original drop down menu.
So for example the original drop box would say "Continent" then drop down to a list of continents, when you select a continent a new box opens that asks you "Country" then you select a country and a new drop box opens to select a state.
I've been using this template
<script type="text/javascript">
function CheckDepartment(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';}
function CheckOption(val){
var element=document.getElementById('misc')
if(val=='misc')
element.style.display='block';
else
element.style.display='block';
}
</script>
</head>
<body>
<select name="color" onchange='CheckDepartment(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<select name="othercolor" id="othercolor" onchange='CheckOption(this.value)' style='display:none;'/>
<option value=""></option>
<option value="hi">hi</option>
<option value="misc" id="misc" >misc</option>
</select>
<select name="third" style='display:none;'>
<option value=""></option>
<option value="first">first</option>
<option value="second">second</option>
</select>
but I can't get a third drop box to open when selecting an option from the second drop box.
edit: third box. I think i deleted my last try so this was kinda a recreation of it from what I remembered. I'm also incredibly new at all of this and don't know if anything I tried makes sense.
Here's a simplified demo.
(It assumes only a "yes" value should trigger the display of the next dependent dropdown.)
const
select1 = document.getElementById("select1"),
select2 = document.getElementById("select2");
document.addEventListener("change", handleDropdownDisplay);
function handleDropdownDisplay(event) {
let changedElement = event.target;
if ((changedElement != select1) && (changedElement != select2)) {
return;
}
if (changedElement.value == "yes") {
changedElement.parentElement.nextElementSibling.classList.remove("hidden");
} else {
changedElement.parentElement.nextElementSibling.classList.add("hidden");
}
}
div {
margin-bottom: 0.5em;
}
.hidden {
display: none;
}
<div>
<label for="select1">Show level 2?</label>
<select id="select1">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select2">Show level 3?</label>
<select id="select2">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select3">Would your rather</label>
<select id="select3">
<option value="brains">Eat monkey brains</option>
<option value="vba">Write code in VBA</option>
</select>
</div>
(Btw, level 3 doesn't automatically become hidden whenever level 2 becomes hidden. This is probably functionality you'll want to add.)

How do I disable, hide, or remove selected option in other selects with the same options?

I'm writing a form with 4 <select> elements. They all have the same options and I would like to disable, hide, or remove the selected option from one <select> in the other <select> elements with the same options in order to prevent the user to select the same option in multiple <select> elements.
No jQuery, only plain JavaScript please.
If possible I would like the first option to always display in all <select> elements:
<option class="select-items" selected>Sélectionnez..</option>
Here is the HTML for one <select>:
<select class="custom-select mb-3" id="name_typage_0">
<option class="select-items" selected>Sélectionnez..</option>
<option class="select-items" value="designation">Désignation</option>
<option class="select-items" value="email">Email</option>
<option class="select-items" value="ville">Ville</option>
<option class="select-items" value="secteur_activite">Secteur d'activité</option>
</select>
Here is part of my JavaScript:
const custSelec = document.querySelectorAll('.custom-select');
custSelec.forEach(function(item){
item.addEventListener('change', function(){
if(item.options[item.selectedIndex].text == 'Sélectionnez..'){
count = -1;
}else{
count = 1;
total += count;
compteur.textContent = ` ${total}/${custSelec.length -1}`;
In your change event listener, you can get the current set of selected values from all <select> elements in the group, and then loop through each element's options to both disable the options currently selected elsewhere in the group as well as re-enable any options that were previously selected but have since been changed. You can avoid disabling the first "label" option in each of your selects by checking the value before disabling / enabling options.
You could use this same approach to hide or remove options keeping in mind that there are some browser compatibility issues when trying to hide <option> elements and that you would need some additional code to store the complete list of options if you were going to remove and restore them.
const selects = document.querySelectorAll('.select-group');
selects.forEach((elem) => {
elem.addEventListener('change', (event) => {
const values = Array.from(selects).map((select) => select.value);
for (const select of selects) {
select.querySelectorAll('option').forEach((option) => {
const value = option.value;
if (value && value !== select.value && values.includes(value)) {
option.disabled = true;
} else {
option.disabled = false;
}
});
}
});
});
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
Thanks a lot for your help! I added a small 'if' to fix my bug and it works perfectly (until the next bug ^^):
if(value !== ""){
option.disabled = true;
}
Or I could just :
if (value && value !== select.value && values.includes(value) && value !== "") {
option.disabled = true;
}
Another difficulty when you begin : learn to write simple code ^^z

javascript to dynamically change the dropdown

Attached the screenshot of my web page.
In that picture, under Regression type dropdown list box, there are three values consider 1, 2 and 3
So if I select 1 or 2, drop down below that "F1" should not appear. If value3, then it should appear.
To do this I have added onload under body tag.
HTML CODE:
<div class = "cl-regr" id="div-regr">
<select name = "regr" id="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class = "cl-ftr" id="div-ftr" onchange="displayFeatureList()">
<select name = "ftr" class = "cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
RESPECTIVE SCRIPT IN SEPARATE .js FILE:
function func1(){
$(".cl-ftr").each(function() {
var that = $(this);
that.find("div.cl2").style.visibility="hidden";
});
};
function displayFeatureList(){
var d_obj = document.getElementById("drop_reg").value;
var op = d_obj.options[d_obj.selectedIndex].value;
if (op == 3){
document.getElementById("drop_ftr").style.visibility = 'visible';
}
else{
document.getElementById("drop_ftr").style.visibility = 'hidden';
}
};
where I'm calling func1 from body tag
<body onload="func1()">
Problems I'm facing are,
1)Whenever the page loads, the "F1" dropdown list box of first row is hiding (ie, ClientIP - 10.213.174.90)
2) If I change the value, displayFeatureList function is not making any effects.
Any help would be much appreciated!!
you are syntax was wrong
$(this) is jquery object style.visiblity its dom function
Use with css() jquery function .style.visiblity is not a jquery object.
For better my suggestion use css .cl2{visiblity:hidden} instead of js
cl2 class in select element not with div so remove the div with cl2 in selector like find('cl2')
fix the id name typo - instead of _
Add change event with first select
Get the value from dropdown direct call the selectelement.value.no need specify index
function func1() {
$(".cl-ftr").each(function() {
var that = $(this);
that.find(".cl2").css('visibility', "hidden");
});
};
function displayFeatureList() {
var d_obj = document.getElementById("drop-regr").value
if (d_obj == '3') {
document.getElementById("drop-ftr").style.visibility = 'visible';
} else {
document.getElementById("drop-ftr").style.visibility = 'hidden';
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="func1()">
<div class="cl-regr" id="div-regr">
<select name="regr" id="drop-regr" onchange="displayFeatureList()">
<option selected="selected" disabled>-----Select-----</option>
<option value = "1"> ips </option>
<option value = "2"> ips sanity </option>
<option value = "3"> Features </option>
</select>
</div>
<div class="cl-ftr" id="div-ftr" >
<select name="ftr" class="cl2" id="drop-ftr">
<option value = "f1"> F1 </option>
<option value = "f2"> F2 </option>
<option value = "f3"> F3 </option>
<option value = "f4"> F4 </option>
</select>
</div>
With all respect, your code quality is not very good.
It's filled with typos (changing _ to -, missing single letters for ids etc.) This way, nothing will ever work. Take more care.
An id has to be unique. If an id appears twice in the same HTML document,
the document is not valid by definition. (It still loads though, but you have to expect errors.) You maybe want to keep the ids an add a dynamic number (row number)to keep them unique
If you use jQuery, use it by default. Don't mix up jQuery(func1()) and JS DOM methods(displayFeatureList)
I reduced your code to the following (I commented the whole JS code for better understanding):
$(document).ready(function() { //run when page loading is complete
$(".regessionTypeCell").each(function() { //for each regessionTypeCell class (parent div, might be a table cell in your case)
$(this).find(".drop-regr").change(function(event) { //set onChange function for the containing drop-regr class
var conditionalDropdown = $(this).find(".cl-ftr"); //get the conditional dropdown element
if ($(this).find(".drop-regr").val() == 3) { //if selected index is equal 3
conditionalDropdown.show(); //show dropdown
} else {
conditionalDropdown.hide(); //hide dropdown
}
}.bind($(this))); //bind this to the inner function
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>
<div class="regessionTypeCell">
<div class="cl-regr">
<select name="regr" class="drop-regr">
<option selected="selected" disabled>-----Select-----</option>
<option value="1"> ips </option>
<option value="2"> ips sanity </option>
<option value="3"> Features </option>
</select>
</div>
<div class="cl-ftr" style="display:none">
<select name="ftr" class="drop-ftr">
<option value="f1"> F1 </option>
<option value="f2"> F2 </option>
<option value="f3"> F3 </option>
<option value="f4"> F4 </option>
</select>
</div>
</div>

Categories