How to refresh a select list in html - javascript

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>

Related

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

Show Value Instead of text in select option

I have country codes dropdown list, in select option text there countryname and ISD Code together, but I want only show ISD Code after Selection.
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
I have searched for some other forums but I am not able to get how to do this. like if we select Anguilla, then it should show +1 there and if it is selected Angola, it should show +244
A solution with only a <select> element.
How it works:
Initializes a hidden <option> that will be used for showing the selected option's value.
When an option is selected:
affects to the hidden option's value attribute and text content the value attribute of the just selected option if this value is not empty. Then shows that hidden option.
empties value and text content of that option, then hides it, if the chosen value is empty (Country code option here).
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select');
select.addEventListener('change', () => {
const value = select.value,
showValueOption = select.querySelector('.show-value');
if (value === '') {
showValueOption.style.display = 'none';
showValueOption.value = '';
return;
}
showValueOption.style.display = '';
showValueOption.innerText = value;
showValueOption.value = value;
select.selectedIndex = 0;
});
});
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option class="show-value" value="" style="display:none;"></option>
<option value="" selected>Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
You can handle change event of select tag like this.
I updated code for display selected value as selected text.
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
})
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
//$("#country_isd_code option:selected").text($(this).val());
$("#selecteditem").val($(this).val())
$("#selecteditem").text($(this).val())
$("#selecteditem").prop('selected', true);
$("#selecteditem").show();
})
#selecteditem{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option id="selecteditem" value=""></option>
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
<input type="text" id="codeselect" />

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>

JavaScript - Dropdown value dependent

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.

how to display selected value from dropdownlist to label using javascript

I have 3 drop-down lists in my form. I want to display the selected value from each dropdown list to my label. The problem is that only one dropbox list will display, while the other two won't.
Here is my code:
<script>
window.onload = function()
{
document.getElementsByName('mydropdown')[0].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
</script>
this is my html
<td><select name="mydropdown" id="mydrop" onchange="">
<option value="none" selected="selected"></option>
<option value="17.50">6M</option>
<option value="25.00">12M</option>
</select>
</td>
<td><label id="mylabel"></label></td>
<td><select name="mydropdown" id="mydrop">
<option value="none" selected="selected">Length </option>
<option value="0.0455">DS516HO</option>
<option value="0.0559">DS520HO</option>
<option value="0.0780">DS516HWR</option>
<option value="0.0200">DS312WH</option>
<option value="0.0624">DS520WH</option>
<option value="0.0361">DS525FH</option>
<option value="0.1170">DS620HW</option>
<option value="0.1340">DS550HW</option>
<option value="0.1340">TD525HW</option>
<option value="0.1820">DS650HW</option>
<option value="0.2340">TD665HWR</option>
</select>
<td><label id="mylabel"></label></td>
You're only binding the zeroth element (the one you selet) with [0]. You need to bind to all of them, possibly like so:
Array.prototype.forEach.call(document.getElementsByName('mydropdown'),
function (elem) {
elem.addEventListener('change', function() {
document.getElementById('mylabel').innerHTML = this.value;
});
});
http://jsfiddle.net/UNLnx/
By the way you are reusing the same ID on multiple elements which is invalid.
Update: Working example: http://jsfiddle.net/x8Rdd/1/
That's because you are only setting the onchange event for the first element in your "mydropdown" group.
<script>
window.onload = function()
{
var dd = document.getElementsByName('mydropdown');
for (var i = 0; i < dd.length; i++) {
dd[i].onchange = function(e)
{
document.getElementById('mylabel').innerHTML = this.value;
};
}
}
</script>
Or something like that. If you're using jQuery then you can set the onchange property for all of them without the loop.

Categories