Show Value Instead of text in select option - javascript

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" />

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>

Display a different default value after selected an option

What I want to achieve is after a user selects an option, the input would then display "select another option" instead of display the value name of the selected option.
Basic example:
<select>
<option value="" selected>Select an Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
Attach a change event listener to the select that checks whether this is the first time the user selected an option. If it is, you can set the value to "" and set the textContent of the selected option to "Select another option."
const select = document.querySelector('select');
var isFirst = true;
select.addEventListener('change', function() {
if (isFirst) {
select.value = "";
select.options[select.selectedIndex].textContent = "select another option";
isFirst = false
}
})
<select>
<option value="" selected>Select an Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
If you want to do it everytime the user selects an option:
const select = document.querySelector('select');
select.addEventListener('change', function() {
select.value = "";
select.options[select.selectedIndex].textContent = "select another option";
})
<select>
<option value="" selected>Select an Option</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>

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

Generate text on a webpage which depends on dropdown box options

I have created a dropdown box with 3 options on my website.
I want to change some text on the webpage, depending on the drop-down item selected. For example:
If dropdown option 1 is chosen, I would like some text on the page that says "You have chosen option 1".
I don't know any JavaScript and so I haven't tried anything apart from trying to search for a similar solution.
<select name="os0" style="background: #315d80; color: #fff; border-color: white; border: 0px;">
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
<option value="op3">Option 3</option>
</select>
Full sultion with jQuery (I started typing it before you added the HTML to your question so the options are italian car brands).
https://jsfiddle.net/mL2c2xb6/
HTML:
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
Javascript:
$('select').change(function(){ // Listen to changes to <select> element
const options = $("option"); // Get all the <option> elements.
let selectedOption = ""; // Var to store selected option value.
options.each(function(index){ // Iterate through option elements.
let option = options[index];
if($(option).prop("selected")) { // Find the seletced one.
selectedOption = $(option).val(); // Get the value and store it
};
});
$("#choiceDisplay")
.empty()
.append(selectedOption); // Display the result.
});
var e = document.querySelector('[name="os0"]');
var strUser = "";
e.addEventListener("change", function(){
strUser = e.options[e.selectedIndex].innerHTML;
alert("You have chosen " + strUser);
});

remove selected value from select box using jquery but It's need to display current selected value in select box?

I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>

Categories