tags:

views:

307

answers:

2

I have a drop-down list and I've bound a change event handler to it. Whenever the user selects a new option, I want to know if it is the last option of the list.

Annoyingly, the relevant condition in the snippet below always returns true, no matter which option has been selected:

        sel.change(function() {
            //this always returns true!
            if(jQuery('#' + this.id + ' option').is(':last')) {
                alert('hello I am the last option');
                inputDiv.show();
                inputDiv.find("input").attr('disabled',false);
            } else {
                inputDiv.hide();
                inputDiv.find("input").attr('disabled',true);
            }
        });

Even if I do this, the result is the same:

if(jQuery('#' + this.id + ' option:selected').is(':last')) {
...

What am I doing wrong? And if you know, why do those tests both evaluate to true?

EDIT: Found the solution:

if(jQuery('#' + this.id + ' option:last').is(':selected')) {
...
}

If anyone knows a better way of doing this, I'm all ears. Thanks.

+4  A: 

Look, no bloat!

 sel.selectedIndex == sel.length-1

That's W3C standard solution.

porneL
I admit, that is better. Thanks.
karim79
I would hav hoped jQuery could hav done this a little more elegantly..
cottsak
True, that doesn't look "jQuerish", but this method is so simple, that it doesn't need any convenience wrapper.
porneL
A: 

Hey, here is another one... and it is "jQuerish" :)

$("select option:last").is(":selected")
simmu