Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

option:selected not working jquery 1.9

Tags:

jquery

The following:

  $("select option:contains(fish)").attr('selected', true);

Works wonderfully in anything below jQuery 1.9, but does not work at all in jQuery 1.9+. I have been searching for any documentation on any change, but have not found anything.

Any idea how to get this code to work with the new jquery?

Example Here (defaults to jQuery 1.4): http://jsfiddle.net/reigel/TZmEw/

like image 838
Ray Suelzer Avatar asked Jan 16 '13 19:01

Ray Suelzer


4 Answers

Use Prop api instead of attr for jquery 1.9.

$("select option:contains(fish)").prop('selected', 'selected');

OR

 $("select option:contains(fish)").prop('selected', true);

Reason : jQuery 1.6 introduced the .prop() method for setting or getting properties on nodes and deprecated the use of .attr() to set properties. However, versions up to 1.9 continued to support using .attr() for specific situations. This behavior in the name of backwards compatibility causes confusion when selectors are used that distinguish between attributes and properties.

Source : http://jquery.com/upgrade-guide/1.9/#changes-of-note-in-jquery-1-9

Mentioned in Attr Api : As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method.

Source : http://api.jquery.com/attr/#entry-longdesc

like image 58
insomiac Avatar answered Nov 14 '22 13:11

insomiac


$("select option:contains(fish)").attr('selected', 'selected');
like image 31
Eric Avatar answered Nov 14 '22 13:11

Eric


Please see the jQuery documentation on the topic with respect to 1.9 specifically. .attr vs. .prop can be confusing since that I know of there is no specific way to know what "properties" are. For all intents and purposes, when changing values that the user has the ability to change .. especially boolean values, you should use .prop

One exception is an input's value -- you should use .val for that. Similarly, it's probably better to use .val to set the <select> elements value -- not easy to do in your case, but it would be more accurate.

jQuery 1.6 introduced the .prop() method for setting or getting properties on nodes and deprecated the use of .attr() to set properties. However, versions up to 1.9 continued to support using .attr() for specific situations.

like image 45
Explosion Pills Avatar answered Nov 14 '22 13:11

Explosion Pills


Try this

$("select option").removeAttr('selected').filter(":contains(fish)").attr('selected', true);
like image 1
Varinder Singh Avatar answered Nov 14 '22 13:11

Varinder Singh