Retrieve all selected options from a multi select - javascript

<select id="abc" multiple="multiple">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">C</option>
</select>
I wish to retrieve all selected values.
No matter what I try it seems to only give me the value of the selected item that is lowest in the list. So if I select A, B, and C it will only return C.
These are the things I have tried:
$('#abc').val()
$('#abc').text()
$('#abc :selected').val()
$('#abc :selected').text()
$('#abc option:selected').val()
$('#abc option:selected').text()
The version of jQuery I am using is v1.9.1

You need to loop through all selected element within select using .each() to get access them individually:
$('#abc :selected').each(function(){
console.log($(this).text());
});
or to get the values in array
var selectedvals = $('#abc').val();
http://jsfiddle.net/spwSL/

You can do:
var values = $("#abc option:selected").map(function() {
return this.value;
}).get();

You can use .map() to store the values in an array and use it:
var vals = $('#abc :selected').map(function(){
return this.value;
}).get();
console.log(vals);
or this way:
var vals = [];
$('#abc :selected').each(function(){
vals.push(this.value);
});
console.log(vals);

For a multiple select when this references the select element, you cannot use this.value as that will return only one value. As #MilindAnantwar has noted above $(this) will return an array. If you were interested in a comma-delimited string rather than an array you can use the join() array method to join the various values into a string:
var selectedOpts = $( '#abc' ).val().join( ',' );
Otherwise you would have to access the elements by array notation [0], [1], .... [n-1].

Related

document.getElementsByName returns null in jquery [duplicate]

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

JQuery get the value of the newly selected/unselected element of a select [duplicate]

I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
}); ​
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.

Set selected value in multiple select list

I have this multi select list:
<select id="vendors" name="vendors" multiple="multiple">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
</select>
When the page loads, I'm loading a list of ids that need to be selected in my select list. Here's how I'm trying to do it:
var vendors = GetVendorArray(); // list of vendor ids I want selected
$.each(vendors, function(index, item) {
$("#vendors").filter(function() {
return $(this).val() == item;
}).attr('selected', true);
});
But this doesn't work, none of the items are being selected. Anyone know what I'm doing wrong?
Simplest approach is just pass the whole array as value to the select using val(). With mulitple select value is an array
$('#vendors').val( GetVendorArray())
DEMO:http://jsfiddle.net/sPKAY/
The problem with approach you took was not looping over option tags
filter reduces the set of matched elements to match the additional selector/callback fn. output. You need to target the <option> elements, not the drop-down list itself, since you're trying to select the option based on whether its value matches your array contents.
var vendors = GetVendorArray(); // list of vendor ids I want selected
$.each(vendors, function(index, item) {
//you're filtering options, not the list itself
$("#vendors > option").filter( function() {
return $(this).val() == item;
}).prop('selected', true); //use .prop, not .attr
});

alert all selected value in SELECT - JQUERY

how can i get all the selected value in tag SELECT?
<select id="list" multiple=multiple>
<option value="1" selected="selected">one </option>
<option value="2" selected="selected">two </option>
<option value="3">three </option>
</select>
for example use foreach as php???
live: http://jsfiddle.net/FMF7c/1/
how can i show with alert in this example one and two? I would like use JQUERY
The val()[docs] method will return an Array for a multiple <select>.
alert( $('#list').val() ); // to show both
$.each( $('#list').val(), function(i,v) { alert( v ); }); // to show individual
Example: http://jsfiddle.net/FdMMK/
$("#list").find("option:selected").each(function() { alert($(this).val()); });
http://jsfiddle.net/yjL9n/1/
I guess just "alerting" those values is not really what you want. To .map() those values into an Array, we can use the below:
var values = $('#list option:selected').map(function(_, node) {
return node.value; // or node.textContent || node.text
}).get();
alert( values );
http://jsfiddle.net/FMF7c/4/
Updated the JSFiddle - http://jsfiddle.net/FMF7c/5/
I've used simple JavaScript to loop through all the options in the select element, and add any of which are selected to an array.
Hah, looks like you didn't need my help after all.

How to get all options of a select using jQuery?

How can I get all the options of a select through jQuery by passing on its ID?
I am only looking to get their values, not the text.
Use:
$("#id option").each(function()
{
// Add $(this).val() to your list
});
.each() | jQuery API Documentation
Without jQuery
I do know that the HTMLSelectElement element contains an options property, which is a HTMLOptionsCollection.
const myOpts = document.getElementById('yourselect').options;
console.log(myOpts[0].value) //=> Value of the first option
A 12 year old answer. Let's modernize it a bit (using .querySelectorAll, spreading the resulting HTMLOptionsCollection to Array and map the values).
// helper to retrieve an array of elements using a css selector
const nodes = selector => [...document.querySelectorAll(selector)];
const results = {
pojs: nodes(`#demo option`).map(o => o.value),
jq: $(`#demo option`).toArray().map( o => o.value ),
}
console.log( `pojs: [${results.pojs.slice(0, 5)}]` );
console.log( `jq: [${results.jq.slice(0, 5)}]` );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="demo">
<option value="Belgium">Belgium</option>
<option value="Botswana">Botswana</option>
<option value="Burkina Faso">Burkina Faso</option>
<option value="Burundi">Burundi</option>
<option value="China">China</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
<option value="India">India</option>
<option value="Japan">Japan</option>
<option value="Malaysia">Malaysia</option>
<option value="Mali">Mali</option>
<option value="Namibia">Namibia</option>
<option value="Netherlands">Netherlands</option>
<option value="North Korea">North Korea</option>
<option value="South Korea">South Korea</option>
<option value="Spain">Spain</option>
<option value="Sweden">Sweden</option>
<option value="Uzbekistan">Uzbekistan</option>
<option value="Zimbabwe">Zimbabwe</option>
</select>
$.map is probably the most efficient way to do this.
var options = $('#selectBox option');
var values = $.map(options ,function(option) {
return option.value;
});
You can add change options to $('#selectBox option:selected') if you only want the ones that are selected.
The first line selects all of the checkboxes and puts their jQuery element into a variable. We then use the .map function of jQuery to apply a function to each of the elements of that variable; all we are doing is returning the value of each element as that is all we care about. Because we are returning them inside of the map function it actually builds an array of the values just as requested.
Some answers uses each, but map is a better alternative here IMHO:
$("select#example option").map(function() {return $(this).val();}).get();
There are (at least) two map functions in jQuery. Thomas Petersen's answer uses "Utilities/jQuery.map"; this answer uses "Traversing/map" (and therefore a little cleaner code).
It depends on what you are going to do with the values. If you, let's say, want to return the values from a function, map is probably the better alternative. But if you are going to use the values directly you probably want each.
$('select#id').find('option').each(function() {
alert($(this).val());
});
This will put the option values of #myselectbox into a nice clean array for you:
// First, get the elements into a list
var options = $('#myselectbox option');
// Next, translate that into an array of just the values
var values = $.map(options, e => $(e).val())
$("#id option").each(function()
{
$(this).prop('selected', true);
});
Although, the CORRECT way is to set the DOM property of the element, like so:
$("#id option").each(function(){
$(this).attr('selected', true);
});
You can take all your "selected values" by the name of the checkboxes and present them in a sting separated by ",".
A nice way to do this is to use jQuery's $.map():
var selected_val = $.map($("input[name='d_name']:checked"), function(a)
{
return a.value;
}).join(',');
alert(selected_val);
Working example
The most efficient way to do this is to use $.map()
Example:
var values = $.map($('#selectBox option'), function(ele) {
return ele.value;
});
You can use following code for that:
var assignedRoleId = new Array();
$('#RolesListAssigned option').each(function(){
assignedRoleId.push(this.value);
});
For multiselect option:
$('#test').val() returns list of selected values.
$('#test option').length returns total number of options (both selected and not selected)
Another way would be to use toArray() in order to use fat arrow function with map e.g:
const options = $('#myselect option').toArray().map(it => $(it).val())
Here is a simple example in jquery to get all the values, texts, or value of the selected item, or text of the selected item
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
printOptionValues = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).val());
})
}
printOptionTexts = () => {
$('#nCS1 > option').each((index, obj) => {
console.log($(obj).text());
})
}
printSelectedItemText = () => {
console.log($('#nCS1 option:selected').text());
}
printSelectedItemValue = () => {
console.log($('#nCS1 option:selected').val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select size="1" id="nCS1" name="nCS1" class="form-control" >
<option value="22">Australia</option>
<option value="23">Brunei</option>
<option value="33">Cambodia</option>
<option value="32">Canada</option>
<option value="27">Dubai</option>
<option value="28">Indonesia</option>
<option value="25">Malaysia</option>
</select>
<br/>
<input type='button' onclick='printOptionValues()' value='print option values' />
<br/>
<input type='button' onclick='printOptionTexts()' value='print option texts' />
<br/>
<input type='button' onclick='printSelectedItemText()' value='print selected option text'/>
<br/>
<input type='button' onclick='printSelectedItemValue()' value='print selected option value' />
var arr = [], option='';
$('select#idunit').find('option').each(function(index) {
arr.push ([$(this).val(),$(this).text()]);
//option = '<option '+ ((result[0].idunit==arr[index][0])?'selected':'') +' value="'+arr[index][0]+'">'+arr[index][1]+'</option>';
});
console.log(arr);
//$('select#idunit').empty();
//$('select#idunit').html(option);
This is a simple Script with jQuery:
var items = $("#IDSELECT > option").map(function() {
var opt = {};
opt[$(this).val()] = $(this).text();
return opt;
}).get();
var selectvalues = [];
for(var i = 0; i < items.length; i++) {
for(key in items[i]) {
var id = key;
var text = items[i][key];
item = {}
item ["id"] = id;
item ["text"] = text;
selectvalues.push(item);
}
}
console.log(selectvalues);
copy(selectvalues);
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
This is a very simple way to generate a list of comma separated values.
var values = "";
$('#sel-box option').each(function () {
values = values + $(this).val() + ";";
});
$("input[type=checkbox][checked]").serializeArray();
Or:
$(".some_class[type=checkbox][checked]").serializeArray();
To see the results:
alert($("input[type=checkbox][checked]").serializeArray().toSource());
If you're looking for all options with some selected text then the below code will work.
$('#test').find("select option:contains('B')").filter(":selected");
The short way
$(() => {
$('#myselect option').each((index, data) => {
console.log(data.attributes.value.value)
})})
or
export function GetSelectValues(id) {
const mData = document.getElementById(id);
let arry = [];
for (let index = 0; index < mData.children.length; index++) {
arry.push(mData.children[index].value);
}
return arry;}
I found it short and simple, and can be tested in Dev Tool console itself.
$('#id option').each( (index,element)=>console.log( index : ${index}, value : ${element.value}, text : ${element.text}) )
$("select#MY_SELECT_ID").find('option').each(function() {
console.log($(this).val());
console.log($(this).text());
});

Categories