I suspect there is a simpler way to find if a select has a certain option, but don't know what. The objective of the following is to check if the desired option exists or not, and if it does, set it as the selected option:
Markup
<input type="text" size="2" id="selectVal"/>
<button onclick="setSelect()">Set the select</button>
<select id="mySelect">
<option value="0">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
JS
function setSelect() {
var desiredOption = $("#selectVal").val();
if (desiredOption == '') {
$("#selectVal").focus();
return false;
}
var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0) {
alert('No such option');
} else {
$('#mySelect').val(desiredOption);
}
$("#selectVal").select();
}
To be clear, I wonder if a single method could do the job of the following two lines:
var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0)
Any suggestions?