aplicar múltiples seleccionados verdaderos a la opción jquery

<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>

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];
                if ( optionsToSelect.indexOf( o.value ) != -1 )
                  o.selected = true;

not working perfectly , it will selects all the four options

preguntado el 12 de junio de 14 a las 10:06

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 -

3 Respuestas

Cambiar y guardar

var optionsToSelect = ['16,24'];


var optionsToSelect = ['16','24'];

This is how to define an array of strings. Else your code works fine.

Demo de trabajo

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.

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

Prueba esto:

var selValues="16,24";
$.each(selValues.split(","), function(i,e){
    $("#testd option[value='" + e + "']").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 or haz tu propia pregunta.