Mitya Ustinov
Mitya Ustinov

Reputation: 903

jQuery. Check if the option element has selected attribute

I have a function that needs to be fired on window load only if there on page is no option elements that has "selected" attribute.

<option value="1" selected="selected">Option</option>

I tried to do this with no luck with next function:

function fireWhenLoad () 
{
if ( $('select option').is(':selected')) {
        alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
    }
};

$(window).load(function(){
    fireWhenLoad();
});

The function alerts "Selected" in every case if options has "selected" attribute and if they don't.

So what am I doing wrong and how can I check if option element has "selected" attribute?

Thank you!

Upvotes: 0

Views: 4420

Answers (3)

Optimus Prime
Optimus Prime

Reputation: 6907

Have you tried,

$('option').each(function(){
    if($(this).is(':selected')){
       alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
    }
});

Upvotes: 0

juju
juju

Reputation: 449

If I understand you correctly, Use $(document).ready() to enure dom elements have been loaded and then loop through the options. You are currently only selecting first option.

$(document).ready(function(){
$("select option").each(function() {
var $this = $(this);
    if ($this.attr("selected") !== undefined) {
        alert("Selected");
    }
    else
    {
        alert("Not Selected");
        runIfNoSelectedOptions();
        return false;
    }
});

});

Upvotes: 1

Sylvain
Sylvain

Reputation: 158

You can use the $.(document).ready() functionality of JQuery to trigger your event.

Upvotes: 0

Related Questions