HTML Selects & jQuery

There are many posts on Stack Overflow on how to SET a HTML select’s selected option using jQuery. Many of the answers say that you should use .attr() as shown below:

Incorrect Method to SET Value of Select:

// "Unselects" the currently selected option.
$('select').find('option:selected').removeAttr('selected');

// Selects the TEKFused option.
$('select').find('option[value="TEKFused"]').attr('selected','selected');

Unfortunately this method is now incorrect due to a change that jQuery has made (According to jQuery’s documentation on .attr()):

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

In plain language, the .attr() method is inconsistent when getting/setting options for a HTML select – sometimes it works, but sometimes it does not.

Proper Method to SET Value of Select:

The proper way to select options it to use the .prop() method:

// "Unselects" the currently selected option.
$('select').find('option:selected').prop('selected',false);

// Selects the TEKFused option
$('select').find('option[value="TEKFused"]').prop('selected',true);

The .prop() method works perfectly and is consistent!!

Proper Method to GET Value of Select:

In order to GET the currently selected options, you should also use .prop():

// Gets the currently selected option and assigns it to a variable.
var selVal = $('select').find('option:selected');

Hopefully this will save you headaches in the future!

Posted in

Leave a Comment





Table of Contents