Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if the currently selected option in a dropdown list is the last one?

Tags:

People also ask

How do I know which option is selected in dropdown?

You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do you check if something is selected in JavaScript?

Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

Which method is used to retrieve the option values from dropdown?

We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements.

How do you display a selected value in a drop down list in HTML?

To get the value of a select or dropdown in HTML using pure JavaScript, first we get the select tag, in this case by id, and then we get the selected value through the selectedIndex property. The value "en" will be printed on the console (Ctrl + Shift + J to open the console).


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')) {
...
}

Does anyone knows a better way of doing this?