People like to say to use .val()
, but as you noticed, it doesn't like to set by text, but by using the index, instead. So you should do a find
to get that, then set by it. But even that is only part of the story. You should first deselect all other options, and set the attribute of the option you want as selected
using the index that you find.
Btw, I hate the $('#myDropDownListID')
syntax because it is useless in SharePoint because it auto-generates GUIDs and puts them after the IDs, forcing you to have to grab it with $('[id*=myDropDownListID]')
, with the *
indicating that it contains
that value, so that is how I will set this up, except I'll leave out the *
because it's unnecessary in this case. But this syntax is also very useful if you want to use $
instead of *
to say it starts with
that value, and you can use title
or name
instead of id
, so it is incredibly versatile, and I wish more people used it.
$(document).ready(function() {
var yourText = "My Custom Value 2";
// Remove all 'selected' attributes from all options
$('select[id="myDropDownListID"] option').removeAttr('selected');
// Get the index for the value you want to set
var idx = $('select[id="myDropDownListID"] option').filter(function() {
return $(this).html() == yourText;
}).val();
// Set the dropdown value by index and set it as selected by text
var dropdownBox = $('select[id="myDropDownListID"]');
dropdownBox.val(idx);
dropdownBox.find('option[value="' + yourValue + '"]').attr('selected','selected'); // note that .val() doesn't do this
dropdownBox.click(); // may be useful and necessary for certain engines to cache the value appropriately
console.log(dropdownBox.html()); // should show you that the selected option is My Custom Value 2
console.log(dropdownBox.val()); // should give you the index 2
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="myDropDownListID">
<option value="1">My Custom Value 1</option>
<option value="2">My Custom Value 2</option>
<option value="3">My Custom Value 3</option>
</select>