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/
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
$("select option:contains(fish)").attr('selected', 'selected');
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.
Try this
$("select option").removeAttr('selected').filter(":contains(fish)").attr('selected', true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With