Migrating jQuery 1.8.3 to 1.9.0 - Replacing deprecated .attr()
Asked Answered
D

1

1

A site I'm working on was built using jQuery v1.8.3. I'm attempting to upgrade to v1.9.0. Using the jQuery Migration plug-in (v.1.0.0), I'm getting messages in the console saying .attr() is deprecated.

In the .js file these two lines are being used:

var branchID = $('select#ddlBranches').attr('value');
$('select#ddlBranches').attr('value', branchID).change();

They're intended to get the value (which is a record ID) of the current selection in the dropdown, and fire the change event on the dropdown, setting it to the indicated value.

The first line results in this message in the console: "property-based jQuery.fn.attr('value') is deprecated"

The second line causes this to show in the console: "property-based jQuery.fn.attr('value', val) is deprecated"

The Upgrade guide discusses .attr(), but I don't see anywhere that mentions what to replace it with.

What am I supposed to replace .attr() with to accomplish the same functionality?

Thanks for anyone's help.

Dogwood answered 30/1, 2013 at 11:21 Comment(0)
I
3

If you want to get/set the value, use the .val() function:

var branchID = $('select#ddlBranches').val();
$('select#ddlBranches').val(branchID).change();
Ikon answered 30/1, 2013 at 11:23 Comment(2)
Thanks, Anthony. This answers my question, but I noticed that I'm using attr() to SET the target attribute on an anchor tag for a new window ($(this).attr('target', '_blank');), but I'm not getting a message in the console from the Migrate plugin. The 1.9 documentation seems to indicate .attr() is completely deprecated, so I would think that the target setting as above would cause the message as well. Any ideas why not?Dogwood
.val() can be both a getter and a setter. .attr() isn't deprecated but is not meant to get the dynamic, user-changed values of form inputs. Setting normal attributes like target is no problem. In contrast, there is no value attribute on a select element (that is, you never write <select value="42"> in your HTML markup).Ottilie

© 2022 - 2024 — McMap. All rights reserved.