Si sus <option>
elementos no tienen value
atributos, a continuación, puedes utilizar .val
:
$selectElement.val("text_you're_looking_for")
obstante, si su <option>
elementos tienen atributos de valor , o podría hacer en el futuro, entonces esto no funcionará, porque siempre que sea posible .val
seleccionará una opción por su atributo value
en lugar de por su contenido del texto. No hay incorporado en el método jQuery que seleccionará una opción por su contenido de texto si las opciones tienen value
atributos, por lo que tendremos que añadir una a nosotros mismos con un simple plugin:
/*
Source: https://stackoverflow.com/a/16887276/1709587
Usage instructions:
Call
jQuery('#mySelectElement').selectOptionWithText('target_text');
to select the <option> element from within #mySelectElement whose text content
is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
return this.each(function() {
var $selectElement, $options, $targetOption;
$selectElement = jQuery(this);
$options = $selectElement.find('option');
$targetOption = $options.filter(
function() {return jQuery(this).text() == targetText}
);
// We use `.prop` if it's available (which it should be for any jQuery
// versions above and including 1.6), and fall back on `.attr` (which
// was used for changing DOM properties in pre-1.6) otherwise.
if ($targetOption.prop) {
$targetOption.prop('selected', true);
}
else {
$targetOption.attr('selected', 'true');
}
});
}
basta con incluir este plugin en algún lugar después agrega jQuery en la página y luego
jQuery('#someSelectElement').selectOptionWithText('Some Target Text');
para seleccionar opciones.
El método plugin utiliza filter
de seleccionar sólo el option
búsqueda de la targetText, y lo selecciona utilizando .attr
o .prop
, dependiendo de la versión jQuery (ver .prop() vs .attr() para la explicación).
Esto es un jsFiddle puede utilizar para jugar con las tres respuestas dadas a esta pregunta, lo que demuestra que éste es el único que funcionar de forma fiable: http://jsfiddle.net/3cLm5/1/
posible duplicado de [jQuery - ajuste del valor seleccionado de un seleccionar control a través de su descripción de texto] (http://stackoverflow.com/questions/496052/jquery-setting-the-selected-value-of-a-select-control-via-its-text-description) –