Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute

$('#operatordelivery').attr('checked', true);

Hi, I am currently working on migrating jQuery version to jQuery-2.1.1 where I could see the warning in the console JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute. I didn't get a clear idea of what this warning explains. Can somebody tell me what does this error means?

like image 384
Sasi Dunston Avatar asked Apr 10 '15 08:04

Sasi Dunston


2 Answers

From JQMIGRATE docs:

JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute

Cause: Prior to jQuery 1.9, $().attr("checked") etc. would sometimes use the checked|selected property instead of the attribute when interacting with non-XML elements, despite the fact that browsers and the HTML specifications allow the properties (current state) to differ from the attributes (initial/default state). This was a holdover from earlier versions of jQuery that did not offer $().prop.

Solution: Boolean properties should generally not be passed to $().attr at all; replace with $().prop unless you truly intend to update the underlying HTML attribute.

Ref: https://github.com/jquery/jquery-migrate/blob/1.x-stable/warnings.md#jqmigrate-jqueryfnattrselected-might-use-property-instead-of-attribute

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

jQuery docs: http://api.jquery.com/prop/

Referenced answer of SO: .prop() vs .attr() and difference between prop() and attr() in jQuery and when to use attr() and prop()

like image 54
Irvin Dominin Avatar answered Nov 15 '22 16:11

Irvin Dominin


With Jquery version 1.9.1+ instead of

$('#operatordelivery').attr('checked', true);
$('#operatordelivery').attr('checked', 'checked');

you have to use this one

$('#operatordelivery').prop('checked', true);

And also, instead of

$('#operatordelivery').attr('checked')

you have to use :

$('#operatordelivery').prop('checked')
like image 45
Ardalan Shahgholi Avatar answered Nov 15 '22 15:11

Ardalan Shahgholi