How to check whether a select box is empty using JQuery/Javascript

AGE picture AGE · Jun 14, 2012 · Viewed 120.3k times · Source

I have a select box that is being populated dynamically from a database. As of right now the population of this check box is working flawlessly.

I have added functionality that consists of a button which on click calls isSelextBoxEmpty. The job of this function is to know whether this particular check box has been populated or not; if it has not then it will simply do nothing.

My problem is in determining whether this select box is empty or not.

Here is a very simplified example of what I am dealing with:

<li>
    <label for="fruit_name">Fruit</label>
    <select name="some_fruit" id="fruit_name" onclick="populate_box('fruit', this);">
    </select>
</li>

My function, which is called from a separate button, looks like this:

function isSelextBoxEmpty(selectBoxId) {
    var selected_value = $('#fruit_name');

    /* More options... still testing the proper way:
    var selected_value = $('#fruit_name').text;
    var selected_value = $('#fruit_name').value;
    var selected_value = $('#fruit_name').length;
    var selected_value = $('#fruit_name option:selected', this);
    var selected_value = document.getElementById('fruit_name');
    var selected_value = document.getElementById('fruit_name').length;
    var selected_value = document.getElementById('fruit_name').value;
    var selected_value = document.getElementById('fruit_name').innerHTML;
    */

    if (selected_value) {
        alert("NOT null, value: " + selected_value);
        // do something
    }
}

Don't worry about what this does and how it does it. Right now what matters to me is that I can't check whether or not the checkbox is empty, I am just not sure how to go about it. I have read a lot through forums and documentation but there are many implications in doing this since it depends on the implementation itself.

For instance using document.getElementById(...)... will not necessarily return false and it depends on how you use it. Also using $("#someID")... in jQuery may or may not produce the desired results. I have already tried many different times as you can see in the commented lines, all of which can be evaluated in the if(...) statement.

Do you have any suggestions or ideas on how to go about achieving this? Thanks in advance!

Answer

Engineer picture Engineer · Jun 14, 2012

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) {