devicifer
devicifer

Reputation: 11

jQuery fails to update custom attribute

http://jsfiddle.net/k3Grd/373/

As you can see from this fiddle, I can set the attribute, but I can't change it after that. Is there a way to fix this so I can update it?

Here's the code, from the fiddle:

<input type="text" id="tester" value="some data">
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>

$(function(){
    $('#tester').attr('readonly', 'readonly');
    $("#one").html($('#tester').attr('readonly'));
    $('#tester').attr('readonly', 'true');
    $("#two").html($('#tester').attr('readonly'));
    $('#tester').attr('readonly', 'BROKEN');
    $("#three").html($('#tester').attr('readonly'));
});

Output:

readonly
readonly
readonly

Edit: Updated code to use an input. I didn't think it would matter.

Edit: Thanks to phillip100 for pointing out that I should be using prop() not attr(). Also, readonly gets set to false with a boolean false, but it's always true with a string.

$('#tester').prop('readonly', false); //correct
$('#tester').prop('readonly', 'false'); //incorrect

http://jsfiddle.net/k3Grd/378/

Upvotes: 0

Views: 80

Answers (2)

alesc
alesc

Reputation: 2780

Change .attr() to .data() and it will work. As @DarkteK pointed out, readonly is only for input fields.

Upvotes: 1

DarkteK
DarkteK

Reputation: 881

How you want to place an attr like readonly to one div, it doesn't make sense.

You can add readonly to inputs, selects, and textarea ....

Upvotes: 1

Related Questions