Search code examples
javascriptjqueryformsselectverification

How can I verify that all select boxes have a selected option through JavaScript or JQuery or...?


I have 2 select boxes on a page with a variable number of options in them.

For instance:

<fieldset>
    <label for="fizzwizzle">Select a Fizzwizzle</label>
    <select name="fizzwizzle" id="fizzwizzle" size="10">
        <option>Fizzwizzle_01</option>
        <option>Fizzwizzle_02</option>
        <option>Fizzwizzle_03</option>
        <option>Fizzwizzle_04</option>
    </select>
</fieldset>
<fieldset>
    <label for="fizzbaggot">Select a Fizzbaggot</label>
    <select name="fizzbaggot" id="fizzbaggot" size="10">
        <option>Fizzbaggot_01</option>
    </select>
</fieldset>

I would like to verify that both of these select boxes have a selected option. My initial thought is to simply use JQuery but I can't seem to figure out how to do that. My attempts so far have been futile but I have the following code that I think should work with the missing link.

function verify_selectboxen_selection() {
    var allSelected = true;

    $('select').each(function() {
      /* if select box doesn't have a selected option */
            allSelected = false;
            break;
    });

    if (!allSelected) {
        alert('You must select a Job and a Disposition File.');
    }
    return allSelected;
}

Seems simple enough. Thoughts?


Solution

  • In jQuery you can use the :selected selector to get the total options selected. This number out to match the number of select's themselves:

    if ($("select").length === $("option:selected").length) {
      // they match
    }