Getting the Key (text) of a selected option in a html5 select - javascript

I am playing around with a select field. I want to access the key(displayed text) of it. This is currently working, but feels kind of stupid.
<select onChange={
(e) => {
console.log('e.target', e.target);
onChangeEvent(e.target.options[event.target.options.selectedIndex].text, e.target.value);
}}>
...
</select>
Is there something better for
e.target.options[event.target.options.selectedIndex].text
without using jQuery, additional modules...

If you don't care about IE:
const select = document.querySelector('.select')
select.addEventListener('change', (e) => {
const selected = e.target.selectedOptions[0]
console.log(selected.text, selected.value)
})
<select class="select">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

Related

Select box Select all / unselect all or select one option restricted multiple options

I have a Select box, I want to select all options with a single click also unselect all with a single click so if the user wants to select another option so just select only 1 option not multiple.
i want to select / unselect all option on this first option click`
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<select>
<option value="all">select all /unselect all</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
`
A Select is usually used to get only ONE value, perhaps you need a checkbox or something like that... but who knows :)
In order to achieve what you want is that you must add an event listener to the Select and try to store the 'real' values in a variable maybe this example helps you out.
// Html
<select id="mySelect">
<option value="all">select all /unselect all</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
// Js
var allValues = [];
function getAllValues(){
return $('#mySelect option').toArray().map(({value}) => value)
}
function selectHandler(event) {
const { target } = event;
if (target && target.value == 'all') {
allValues = getAllValues()
} else {
allValues = [target.value]
}
// Do something with this
console.log(allValues)
}
$('#mySelect').on('change', selectHandler)

Selecting Item from First Select Box to Populate Second Select Box

I have a form with two select fields. The first select field will list items, the second select field will start empty but be populated by selecting an item from the first and pressing the add button. You would also be able to do the same. You can select an item from the second select field and hit the remove to add it back to the first select field. In the end, I want all the values of the second select field to be in a hidden form box separated by commas.
I've come across examples of this with javascript in the past, but now that I need them I can't seem to find them. Does anyone know of any sources that could show me how to accomplish something like this? At first, I was thinking of doing it using ajax but I would rather do it without loading another page. Any help in pointing me in the right direction would be greatly appreciated! Thanks in advance!
<form name="SelectItem">
<select name="SelectItem">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button>Add =></button>
<button><= Remove</button>
<select name="SelectedItems">
<option value=""></option>
</select>
</form>
You can use jquery append() to do it:
$(document).ready(function(){
$('.add').click(function(){
$('#select1').find('option:selected').appendTo('#select2');
});
$('.remove').click(function(){
$('#select2').find('option:selected').appendTo('#select1');
});
});
Working pen
You can use the add() and remove() methods on the select element:
const select1 = document.getElementById('select1')
const select2 = document.getElementById('select2')
const addItem = () => {
event.preventDefault();
if(select1.length === 0) return;
let itemIndex = select1.selectedIndex;
let item = select1.options[itemIndex];
select1.remove(itemIndex)
select2.add(item);
}
const removeItem = () => {
event.preventDefault();
if(select2.length === 0) return;
let itemIndex = select2.selectedIndex;
let item = select2.options[itemIndex];
select2.remove(itemIndex)
select1.add(item);
}
document.getElementById('addButton').addEventListener('click', addItem);
document.getElementById('removeButton').addEventListener('click', removeItem);
<form name="SelectItem">
<select name="SelectItem" id="select1">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="addButton">Add =></button>
<button id="removeButton"><= Remove</button>
<select name="SelectedItems" id="select2">
</select>
</form>
Below is one relatively simple approach you can take that takes advantage of event delegation technique:
const inSelectEl = document.querySelector('#in-item-list');
const outSelectEl = document.querySelector('#out-item-list');
const optionQuantity = inSelectEl.options.length;
const onClick = e => {
if (e.target.tagName !== 'BUTTON') {
return;
}
let a, b;
if (e.target.id === 'add') {
a = inSelectEl;
b = outSelectEl;
} else {
a = outSelectEl;
b = inSelectEl;
}
const selectedOption = a.options[a.selectedIndex];
b.options[b.options.length] = selectedOption;
}
document.querySelector('#container').addEventListener('click', onClick);
<!-- Added container to enable event delegation -->
<div id="container">
<select name="SelectItem" id="in-item-list">
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
<option value="item3">Item 3</option>
</select>
<button id="add">Add =></button>
<button id="remove"><= Remove</button>
<select name="SelectedItems" id="out-item-list" />
</div>

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

How to select multiple options if check option from a different select?

I want select multiple option from second select depending on check option from first select.
For example:
adiunkt -> mikroklimat, RTG
agent celny -> zapylenie
First select:
<select name="form[stanowisko][]" id="stanowisko">
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
Second select:
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat">mikroklimat</option>
<option value="RTG">RTG</option>
<option value="zapylenie">zapylenie</option>
</select>
I tried this but it not working (select all options after first check):
function tes(){
if (document.getElementById('stanowisko').value ="agent celny") {
document.getElementById('czynniki_szkodliwe').options[2].selected = true;
document.getElementById('czynniki_szkodliwe').options[0].selected = true;
}
if ( document.getElementById('stanowisko').value="adiunkt") {
document.getElementById('czynniki_szkodliwe').options[1].selected = true;
}
}
Pure js solution.
let elem1 = document.getElementById('stanowisko'),
elem2 = document.getElementById('czynniki_szkodliwe');
elem1.addEventListener('change', (e) => {
Array.from(elem2.children).forEach(v => {
return v.disabled = v.getAttribute('data-attr') !== e.target.value;
})
});
<select name="form[stanowisko][]" id="stanowisko">
<option value="">-</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat" disabled data-attr='adiunkt'>mikroklimat</option>
<option value="RTG" disabled data-attr='adiunkt'>RTG</option>
<option value="zapylenie" disabled data-attr='agent celny'>zapylenie</option>
</select>
You should use a data attribute to mark the options linked to the first select like this:
$(document).ready(function(){
$("#stanowisko").on("change", function(event){
var $options = $("#czynniki_szkodliwe option");
//Unselect all
$options.prop("selected", false);
var val = $("#stanowisko").val();
$options.each(function(idx, item) {
if($(item).data("stanowisko").indexOf(val) >= 0) {
$(item).prop("selected", true);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="form[stanowisko][]" id="stanowisko">
<option value="">Choose</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
<option vlaue="lekarz">lekarz</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option data-stanowisko='["adiunkt"]' value="mikroklimat">mikroklimat</option>
<option data-stanowisko='["adiunkt","lekarz"]' value="RTG">RTG</option>
<option data-stanowisko='["agent celny"]' value="zapylenie">zapylenie</option>
</select>
Edit: If several options, from the first select, refers to the same options in the second select, you can "store" an array in the data attribute in JSON format.
I updated the JS code to handle JSON array in the data attributes instead of a simple string.

How do I get selected value from a bootstrap select drop down

I'm trying to get the selected text, not value, from my bootstrap drop down, but my .text() statement is returning a string that contains all the values with a '\n' in between.
Here is my rendered html
<select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
<option selected="selected" value="0">1-4</option>
<option value="1">5-9</option>
<option value="2">10-15</option>
<option value="3">16-20</option>
<option value="4">20+</option>
</select>
Here is my javascript, but selectedText returns '5-9\n10-15\n16-20\n20+'
I want it to return 5-9 or 10-15, etc..
$('#SpaceAccommodation').change(function () {
var selectedText = $(this).text();
});
You can get the selected value's text with $(this).find("option:selected").text().
$('#SpaceAccommodation').change(function () {
var selectedText = $(this).find("option:selected").text();
$(".test").text(selectedText);
});
<script src="https://code.jquery.com/jquery-1.6.4.min.js"></script>
<select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
<option selected="selected" value="0">1-4</option>
<option value="1">5-9</option>
<option value="2">10-15</option>
<option value="3">16-20</option>
<option value="4">20+</option>
</select>
<div class="test"></div>
Fiddle for you
$(document).ready(function () {
$('.chzn-select').change(function () {
alert( $('.chzn-select option:selected').text());
});
});
<select id="second" class="chzn-select" style="width: 100px">
<option value="1">one</option>
<option value="2">two</option>
</select>
This is based on the css3 psuedo-class :selected. It's very similar to :checked, I couldn't find docs for :selected
In case anyone cares, I've got another solution. I just looked at the arguments from the docs. You can do something like this (Assuming you've set the value tag of the option element.:
$('#type_dropdown')
.on('changed.bs.select',
function(e, clickedIndex, newValue, oldValue) {
alert(e.target.value);
});
});
See https://silviomoreto.github.io/bootstrap-select/options/

Categories