4

Possible Duplicate:
.prop() vs .attr()

Please take a look at this fiddle:

http://jsfiddle.net/DGzvP/

$("#test").prop({
    checked: true,
    disabled: true
});

$("#result").text($("#container").html());

You will see the output is:

<input disabled="disabled" id="test" type="checkbox"> 

This is in FF 5. Why does it add an attribute for disabled and not for checked? I was hoping it would do both in a consistent way.

EDIT:

I realize now the result is completely different in every browser.

More Results:

IE6/7:

<INPUT id=test disabled type=checkbox CHECKED> 

Chrome 13:

<input id="test" type="checkbox" disabled="">

IE8:

<INPUT id=test disabled type=checkbox> 
Community
  • 1
  • 1
Dave L.
  • 9,595
  • 7
  • 43
  • 69

2 Answers2

3

The ".prop()" method is all about setting/getting properties on DOM nodes, and not about setting attributes. As such, it doesn't add any attributes. What you're seeing is the behavior of the Firefox 5 "innerHTML" code, and not that of jQuery.

If you want to work with attributes of the HTML or XHTML (or whatever your DOM came from), use ".attr()". For most purposes in JavaScript working with the live DOM, however, you should use ".prop()".

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Note that in 1.8.3 at least, using `prop()` for `disabled` will indeed disable an input that is lacking the `disabled` attribute, and will even report that it's disabled when you check with `attr`! – Charles Wood Sep 26 '14 at 23:41
0

You should use attr instead of prop here.

$("#test").attr({
    checked: true,
    disabled: true
});
Vanni Totaro
  • 5,211
  • 2
  • 28
  • 42
  • He specifically said 1.6.2, which uses the .prop() function to modify properties. @see [.prop()](http://api.jquery.com/prop/) – Andrew Jul 21 '11 at 21:04
  • @Andrew: yeah, *here* in my answer means *to get what you expected*, i.e. ``. – Vanni Totaro Jul 21 '11 at 21:06
  • @Andrew: and he said "why does it add an attribute for disabled and not for checked?", so OP has not clear in mind the difference between attribute and property. I just guessed what he wants to obtain. – Vanni Totaro Jul 21 '11 at 21:10