¿Cómo obtener todos los valores seleccionados de un cuadro de selección múltiple?
Tengo un elemento <select>
con el atributo multiple
. ¿Cómo puedo obtener los valores seleccionados de este elemento usando JavaScript?
Esto es lo que estoy intentando:
function loopSelected() {
var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
var selectedArray = new Array();
var selObj = document.getElementById('slct');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj.value = selectedArray;
}
13 answers
No hay jQuery:
// Return an array of the selected opion values
// select is an HTML select element
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
Ejemplo rápido:
<select multiple>
<option>opt 1 text
<option value="opt 2 value">opt 2 text
</select>
<button onclick="
var el = document.getElementsByTagName('select')[0];
alert(getSelectValues(el));
">Show selected values</button>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-03 08:58:08
Check it Out:
HTML:
<a id="aSelect" href="#">Select</a>
<br />
<asp:ListBox ID="lstSelect" runat="server" SelectionMode="Multiple" Width="100px">
<asp:ListItem Text="Raj" Value="1"></asp:ListItem>
<asp:ListItem Text="Karan" Value="2"></asp:ListItem>
<asp:ListItem Text="Riya" Value="3"></asp:ListItem>
<asp:ListItem Text="Aman" Value="4"></asp:ListItem>
<asp:ListItem Text="Tom" Value="5"></asp:ListItem>
</asp:ListBox>
JQUERY:
$("#aSelect").click(function(){
var selectedValues = [];
$("#lstSelect :selected").each(function(){
selectedValues.push($(this).val());
});
alert(selectedValues);
return false;
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-03 07:16:49
ES6
[...select.options].filter(option => option.selected).map(option => option.value)
Donde select
es una referencia al elemento <select>
.
Para desglosarlo:
-
[...select.options]
toma la lista de opciones tipo Array y la desestructura para que podamos usar Array.métodos prototipo en él (Editar: también considere usarArray.from()
) -
filter(...)
reduce las opciones a solo las que están seleccionadas -
map(...)
convierte los elementos raw<option>
en sus respectivos valores
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-09 01:42:28
Casi lo mismo que ya se sugirió, pero un poco diferente. Casi tanto código como jQuery en Vanilla JS :
selected = Array.prototype.filter.apply(
select.options, [
function(o) {
return o.selected;
}
]
);
Parece ser más rápido que un bucle en IE, FF y Safari. Me parece interesante que es más lento en Chrome y Opera.
Otro enfoque sería usar selectores:
selected = Array.prototype.map.apply(
select.querySelectorAll('option[selected="selected"]'),
[function (o) { return o.value; }]
);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-29 20:19:34
Supongamos que el multiSelect es el Multiple-Select-Element, simplemente use su propiedad selectedOptions:
//show all selected options in the console:
for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
console.log( multiSelect.selectedOptions[i].value);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-28 16:01:38
Aquí hay una implementación ES6:
value = Array(...el.options).reduce((acc, option) => {
if (option.selected === true) {
acc.push(option.value);
}
return acc;
}, []);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-15 18:55:28
Puedes probar este script
<!DOCTYPE html>
<html>
<script>
function getMultipleSelectedValue()
{
var x=document.getElementById("alpha");
for (var i = 0; i < x.options.length; i++) {
if(x.options[i].selected ==true){
alert(x.options[i].value);
}
}
}
</script>
</head>
<body>
<select multiple="multiple" id="alpha">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
<input type="button" value="Submit" onclick="getMultipleSelectedValue()"/>
</body>
</html>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-14 10:44:00
Puede usar [].reduce
para una implementación más compacta del enfoque de RobG :
var getSelectedValues = function(selectElement) {
return [].reduce.call(selectElement.options, function(result, option) {
if (option.selected) result.push(option.value);
return result;
}, []);
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:54:56
Igual que la respuesta anterior pero usando el subrayado.js.
function getSelectValues(select) {
return _.map(_.filter(select.options, function(opt) {
return opt.selected; }), function(opt) {
return opt.value || opt.text; });
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-08 18:39:31
Mi ayudante de plantilla se ve así:
'submit #update': function(event) {
event.preventDefault();
var obj_opts = event.target.tags.selectedOptions; //returns HTMLCollection
var array_opts = Object.values(obj_opts); //convert to array
var stray = array_opts.map((o)=> o.text ); //to filter your bits: text, value or selected
//do stuff
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-07 01:38:27
Riot js code
this.GetOpt=()=>{
let opt=this.refs.ni;
this.logger.debug("Options length "+opt.options.length);
for(let i=0;i<=opt.options.length;i++)
{
if(opt.options[i].selected==true)
this.logger.debug(opt.options[i].value);
}
};
//**ni** is a name of HTML select option element as follows
//**HTML code**
<select multiple ref="ni">
<option value="">---Select---</option>
<option value="Option1 ">Gaming</option>
<option value="Option2">Photoshoot</option>
</select>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-08 11:38:29
Puede utilizar el plugin jquery elegido .
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css"
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
});
</script>
</head>
<body>
<label for="Test" class="col-md-3 control label">Test</label>
<select class="chosen" style="width:350px" multiple="true">
<option>Choose...</option>
<option>Java</option>
<option>C++</option>
<option>Python</option>
</select>
</body>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-15 06:28:05
Basándose en la respuesta de Rick Viscomi , intente usar la propiedad del elemento HTML Select selectedOptions:
let txtSelectedValuesObj = document.getElementById('txtSelectedValues');
[...txtSelectedValuesObj.selectedOptions].map(option => option.value);
En detalle,
-
selectedOptions
devuelve una lista de elementos seleccionados. - Específicamente, devuelve un solo lectura HTMLCollection que contiene HTMLOptionElements.
-
...
es sintaxis de propagación . Expande los elementosHTMLCollection
. -
[...]
crea un objeto mutableArray
a partir de estos elementos, dándote una matriz deHTMLOptionElements
. -
map()
reemplaza cadaHTMLObjectElement
en el array (aquí llamadooption
) con su valor (option.value
).
Denso, pero parece funcionar.
Cuidado, selectedOptions
no es compatible con por IE!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-29 21:01:04