HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Check if select has a certain option

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
checkhasoptionselectcertain

Problem

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


Set the select

    Select an option
    A
    B
    C
    D


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.

Solution

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/

Code Snippets

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();
}

Context

StackExchange Code Review Q#4476, answer score: 4

Revisions (0)

No revisions yet.