I have a select control, and in a javascript variable I have a text string.
Using jQuery I want to set the selected element of the select control to be the item with
I found that by using attr
you would end up with multiple options selected when you didn't want to - solution is to use prop
:
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
$('#theYear').on('change', function () {
FY = $(this).find('option:selected').text();
$('#theFolders').each(function () {
$('option:not(:contains(' + FY + '))', this).hide();
});
$('#theFolders').val(0);
});
$('#theYear').on('mousedown', function () {
$('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
});
Easiest way with 1.7+ is:
$("#myDropDown option:text=" + myText +"").attr("selected", "selected");
1.9+
$("#myDropDown option:text=" + myText +"").prop("selected", "selected");
Tested and works.
Try
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
[...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
<select id="mySelect">
<option value="A">Text A</option>
<option value="B">Text B</option>
<option value="C">Text C</option>
</select>
I do it on this way (jQuery 1.9.1)
$("#my-select").val("Dutch").change();
Note: don't forget the change(), I had to search to long because of that :)
I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above. I ended up using the following code (variation of spoulson's solution):
var textToSelect = "Hello World";
$("#myDropDown option").each(function (a, b) {
if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
});
Hope it helps someone.