how to get last selected option in multiple select in javascript [duplicate] - javascript

This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 11 days ago.
I want to get the last selected <option> in a <select multiple> in javascript not jquery!
The last selected option means the last option selected by the user.
Not that the last option element in the select element!
I try:
<select multiple="multiple" onchange="changeEvent(this)">
function changeEvent(selectTag) {
console.log(selectTag.value);
}
I expected to get the last <option> selected

The value property of the select tag only returns the value of the selected option if the multiple attribute is not set. If the multiple attribute is set, you can use the options property of the <select> element to get an array of all the options and check which ones are selected.
Here's an updated version of the function with JavaScript:
function changeEvent(selectTag) {
let selectedOptions = [];
for (let i = 0; i < selectTag.options.length; i++) {
if (selectTag.options[i].selected) {
selectedOptions.push(selectTag.options[i].value);
}
}
console.log(selectedOptions);
}
<select multiple="multiple" onchange="changeEvent(this)">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
<option value="option4">Option 4</option>
<option value="option5">Option 5</option>
</select>

To get all the selected options, use selectedOptions on the selectTag.
For the 'last' option, use the default selectTag.value.
Remember that .value will only contain the last selected value, so if you'd un-select some value, the previous selected will be set as value of selectTag.value
function changeEvent(selectTag) {
const allSelectedValues = Array.from(selectTag.selectedOptions).map(t => t.value).join(', ');
console.log(`All selected: ${allSelectedValues}`);
console.log(`Previous: ${selectTag.value}`);
}
<select multiple="multiple" onchange="changeEvent(this)">
<option>foo</option>
<option>bar</option>
<option>foobar</option>
</select>

Related

I need to set a select to selected using data-val

I have a select I need to set to selected but the select is using a name and the options are using "data-val" and I can't change either:
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 2</option>
</select>
How can I set Option 2 to selected using JavaScript?
A couple ways that you could go about this;
You could be very explicit and set the value of the <select /> itself through;
document.querySelector('[name="properties[Liner]"]').value = "Option 2";
Or you could be a little bit more dynamic with the following;
document.querySelector('[name="properties[Liner]"]').value = document.querySelector('[data-val="2"]').value;
For the targeting of the name, you'll want to use [name="{some name}"]
For the targeting of a data-attribute, you'll want to use [data-val="{some value}"]
In this scenario, you could just specify "name" for querySelector and you'll get what you want because there's only one element with a name on the page (at least in your mini-scenario).
Code explanation in comments
(function(){
const selectEle = document.querySelector('[name="properties[Liner]"]'); // query the select the element
const setSelected = 2; // set the default value
const options = selectEle.querySelectorAll('option'); // query all the option element
options.forEach((option)=>{
const value = option.getAttribute('data-val'); // get the attribute data-val
if(value == setSelected){ // if matches
option.setAttribute('selected', true); // set selected
}
});
})();
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 3</option>
</select>

I know part of the value of a select option, I would like set that option with JS?

I would like to set an option in a select element based on the substring which will be contained in one of the option values. I have a solution but it seems quite convoluted to me.
I get the values of the options and put them in an array, loop through the values and check if the value includes a string I am looking for when it does I set that value as the select value. There must be an easier way!
I get the values of the options in the following way.
// Get the select element where you can select a procinve with a pull-down
var provincePullDown = document.querySelector(".select-provincie");
// Array containing the values of the select options
var optArray = Array.from(provincePullDown.options);
var optArrayValues = [];
optArray.forEach(el => optArrayValues.push(el.value));
I then loop over the values looking with a likely substring.
// Loop over the values in the select options
optArrayValues.forEach(function (el) {
// Look for the option containing the right province
if (el.includes(selectedProvince)) {
// Set the selected option from the select element
provincePullDown.value = el;
}
});
The option values look something like this sting (3) and the substring like this string.
I would like to know if there is an easier way as to me this seems an overly convoluted solution. And keeping maintenance in mind I would like an clear solution that I will still easily understand in 6 months.
The page is created by Drupal so I also control what html is outputted and the option values are inserted in the Drupal template.
Let me also state that I am not a fan of jQuery even though the project does load jQuery by default.
As querySelector() support any valid CSS selector, you can try with contains (*=) Attribute selector:
[attr*=value]
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
var selectedProvince = 'province';
document.querySelector(".select-provincie option[value*='"+selectedProvince+"']").selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can also use Template Literals for cleaner syntax:
var selectedProvince = 'province';
document.querySelector(`.select-provincie option[value*='${selectedProvince}']`).selected = true;
<select class="select-provincie">
<option value="prov-1">Province 1</option>
<option value="prov-2">Province 2</option>
<option value="province-test">Province 3</option>
<option value="prov-3">Province 4</option>
</select>
You can directly point to the option value if the regext is just a simple contain
const optToSelect = document.querySelector('option[value*=${SUBSTRING}]');
document.querySelector("select").selectedIndex = optToSelect.index;
You can use plain DOM methods with find and includes:
function updateOther(source) {
let value = source.value;
let sel = document.querySelector('.select-provincie');
sel.selectedIndex = [].find.call(sel.options, opt => opt.value.includes(value)).index;
}
<select onchange='updateOther(this)'>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select class="select-provincie">
<option value="province1" selected>Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
But it's not fault tolerant: if a suitable value isn't found, it will throw an error (as do other answers). :-)
JQuery is interesting precisely when you want simplify solutions and ensure it is practical in terms of optimization. So I want to bring you a JQuery solution.
var selectedProvince = 'province3';
$(".select-provincie > option").each((index, elem) => {
if (elem.value == selectedProvince) {$(elem).attr('selected', true)};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="select_provincie">
<select class="select-provincie">
<option value="province1">Province 1</option>
<option value="province2">Province 2</option>
<option value="province3">Province 3</option>
<option value="province4">Province 4</option>
</select>
</div>

sort a dropdown list with added atrribute or id

Currently I am working on a site where I do not have access to the perl generated options of a drop down list. The drop downs are populated dynamically and not all options are available to all users.
The code I am able to work with is shown here.
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;" ></select>
PRIMARY_POS
populates each option that is able to be selected.
The actual output as seen when the page renders is
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;">
<option value="0">None Selected
<option value="155935">Option4
<option value="155934">Option3
<option value="155905">Option2
<option value="155933">Option1
<option value="155932">Option5
</select>
What I need to be able to do is set a sort order based on a hidden attribute that is assigned based on the text value
So in the above example. I need the drop downs ( Important as their are mulitple drop downs on the page ) to be able to be sorted by a not yet created attribute
So that the above code might then be
<option value="0">None Selected
<option sortvalue="5" value="155935">Option4
<option sortvalue="4" value="155934">Option3
<option sortvalue="3" value="155905">Option2
<option sortvalue="2" value="155933">Option1
<option sortvalue="1" value="155932">Option5
</select>
The sortvalue being set base don the Text value of the option select. So that a sortvalue of 5 would be assign to Option4. Just a smaple as the text will need to be assigned.
End result should be that the Drop down list now has a custom attribute of Sortvalue and the select drop down is now sorted by that value.
Once again, I can not directly change the attributes but can manipulate the results. Hope that was easy to follow, which I doubt :/
You can create an object where the keys are the text and values are sort order. Then loop over options and add attribute based on that map
var optsMap = {
"Option4": 5,
"Option5": 1
......
};
var $select = $('select[name=PRIMARY_POS]')
$select.find('option').attr('data-sortvalue', function(){
return optsMap[$(this).text()] ||0;
}).sort(function(a,b){
return +($(a).data('sortvalue')||0) - +($(b).data('sortvalue')||0);
}).appendTo($select);
You can then read the value using:
$select.change(function(){
alert($(this).find(':selected').data('sortvalue'));
})
If all you are needing is sorting and don't need attribute can remove one step
DEMO
Common practice is to prefix those "added attributes" with data. You could try something like this with jQuery, if I'm understanding you correctly.
Example fiddle: https://jsfiddle.net/30cvudz8/7/
<select class="my-select">
<option data-sort-value="3" value="1">Option 1</option>
<option data-sort-value="5" value="2">Option 2</option>
<option data-sort-value="4" value="3">Option 3</option>
<option data-sort-value="1" value="4">Option 4</option>
<option data-sort-value="2" value="5">Option 5</option>
</select>
var optionList = new Array();
$('select.my-select option').each(function() {
optionList[optionList.length] = $(this).attr('data-sort-value')+'::'+$(this).val();
});
optionList.sort(); // sort it
var newOptionList = '';
for(var i = 0; i < optionList.length; i++) {
// recreate option
var parts = optionList[i].split('::');
newOptionList += '<option value="'+parts[1]+'" data-sort-value="'+parts[0]+'">Option '+parts[1]+'</option>';
}
// wipe and repopulate the select list
$('select.my-select').html(newOptionList);
To add an attribute (like data-sort-value) after you have a select list, you can do something like this:
$('select.original option').each(function() {
var sortingValue = getSortingValueFromText($(this).text());
$(this).attr('data-sort-value', sortingValue);
});

How to determine which options selected in multiple <select>? [duplicate]

This question already has answers here:
Get selected value of a dropdown's item using jQuery
(31 answers)
Closed 8 years ago.
I have this <select>:
<select id="week" multiple="multiple" >
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
<option value="7">Sunday</option>
</select>
How can I know that whether each <option> is selected or not in jQuery or JS?
Try to use :selected selector to grab the selected option elements,
$('#week option:selected').each(function(){
//Your code to manipulate things over selected option elements
});
You need to use .is :
$('#week option').each(function() {
if($(this).is(':selected')){
//code
}
});
You can use length property of selected and total options, see below jquery :
var totalOptions = $('#week option').length; // all options available
var selectedOptions = $('#week option:selected').length;// selected options
if(totalOptions == selectedOptions)
alert('All options selected');
else
alert('Not all options selected');

Get value of selected option from drop down using jquery.

I have a problem when I get the values ​​of Selected options.
Let me explain I have a list of options :
<select>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
<option value='4'>Option4</option>
<option value='5'>Option5</option>
</select>
I get the values ​and I inserts them into a variable for each Selected option and I put them in an array like this :
$("select option:selected").each(function()
{
var listValO = new Array();
var idOption = $("select option:selected").val();
listValO.push(idOption);
});
If I choose only one selected option, it works but when I select several options at the same time, the each () function inserts in the array the same value for the number of selected options.
when I click on the submit button, the array contains listValO several times the same value.
<select>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
listValO returns just 3 times [1,1,1]. In fact, it seleted the first which I clicked or I want in my array [1,2,3].
Sorry for English mistakes if any. I hope you understand my problem and thank you for your future response.
As well as the other answers (using multiple attribute, and using $(this)), you are re-declaring the array for each occurrence of a selected option. Try declaring it outside:
var listValO = new Array();
$("select option:selected").each(function()
{
var idOption = $(this).val();
listValO.push(idOption);
});
Firstly, you need to add the multiple attribute to the select so you can select multiple options. Second, you're redeclaring a new array inside the each callback, so at the end you'll only ever have one option.
You should use .val() instead:
Markup:
<select multiple>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Javascript:
var optionsArray = $("select").val();
You need to add attribute multiple in select to select multiple value:
<select multiple="multiple">
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Js code: You are iterating over the selected options, you should rather iterate over to select itself to ensure that selected options are added to array once only.
var listValO = new Array();
$("select").each(function()
{
listValO.push($(this).val());
});
//console.log(listValO) for test purpose
Working Demo

Categories

Resources