Check if select has a certain option 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

&lt;input type="text" size="2" id="selectVal"/&gt;
&lt;button onclick="setSelect()"&gt;Set the select&lt;/button&gt;
&lt;select id="mySelect"&gt;
    &lt;option value="0"&gt;Select an option&lt;/option&gt;
    &lt;option value="1"&gt;A&lt;/option&gt;
    &lt;option value="2"&gt;B&lt;/option&gt;
    &lt;option value="3"&gt;C&lt;/option&gt;
    &lt;option value="4"&gt;D&lt;/option&gt;
&lt;/select&gt;


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?

jsfiddle here.
You could try and force the option to be selected.  Because jQuery doesn't throw errors when it doesn't have a set of elements, you can use this to your advantage inside an if statement. Couple this with jQuery's chaining and you can do something like:

function setSelect() {
    var desiredOption = $("#selectVal").val();
    if (desiredOption == '') {
        $("#selectVal").focus();
        return false;
    }
    if (!$('#mySelect option[value="' +desiredOption+ '"]').prop("selected", true).length) {
        alert('No such option');
    }
    $("#selectVal").select();
}



  Updated fiddle: http://jsfiddle.net/SPvrA/7/