aplicar múltiples seleccionados verdaderos a la opción jquery
Frecuentes
Visto 280 equipos
0
<select id="testd" name="testd[]" multiple="" style="min-height: 100px;">
<option value="16">test1</option>
<option value="21">test2</option>
<option value="27">test3</option>
<option value="24">test4</option>
</select>
how to apply seleted true to multiple option , example 16,24 , want to apply seleted true to option
Lo intenté
var optionsToSelect = ['16,24'];
var select = document.getElementById( 'testd' );
for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
o = select.options[i];
console.log(o);
if ( optionsToSelect.indexOf( o.value ) != -1 )
{
o.selected = true;
}
}
not working perfectly , it will selects all the four options
3 Respuestas
3
Cambiar y guardar
var optionsToSelect = ['16,24'];
a
var optionsToSelect = ['16','24'];
This is how to define an array of strings. Else your code works fine.
Respondido el 12 de junio de 14 a las 10:06
Sencillo $("#testd").val(['16','24']);
will do. I have modified @Alek example for demo codepen.io/anon/pen/whlkE - Satpal
@Satpal , that looks great, but i think OP is not using jQuery, though the tag exists. - Shaunak D.
0
El problema es que optionsToSelect
is not proper, you need to store the different ids in separate indexes in the array
Since you are using jQuery try
var optionsToSelect = [16, 24];
$('#testd option').filter(function () {
return $.indexOf(+this.value, optionsToSelect) >= 0
}).prop('selected', true)
Respondido el 12 de junio de 14 a las 10:06
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas javascript jquery html or haz tu propia pregunta.
As you have tagged your question with jQuery. Simple
$("#testd").val(['16','24']);
will do the job for you. Just note: tag your questions properly - Satpal