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



    <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?



    jsfiddle here.


  • Andy E

    Andy E Correct answer

    10 years ago

    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/



    Thanks. If indeed forcing selection of non-existing options does not throw an error (have not tested that in mainstream browsers), for my present use case that is all I care for.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM