Hacker
Hacker

Reputation: 7906

Make textarea readonly with jquery

For text input I do:

$('input[type="text"]').each(function(){
  $(this).attr('readonly','readonly');
});

But what should I do for textarea, to make it readonly.

Upvotes: 48

Views: 94144

Answers (5)

Manu Manjunath
Manu Manjunath

Reputation: 6411

In latest versions of jQuery, the use of method prop is preferred over use of attr.

To make a particular textarea readonly:
$('#mytextarea1').prop('readonly', true);

To make all textareas readonly:
$('textarea').prop('readonly', true);

To make all 'text' fields readonly:
$('input[type=text]').prop('readonly', true);

To make all 'text' fields and textarea readonly:
$('input[type=text],textarea').prop('readonly', true);

Please also note the difference between 'readonly' and 'disabled' in terms of appearance:

Below is a <textarea> with disabled set to true:
Textarea disabled(looks different from a regular textarea)

Below is a <textarea> with readonly set to true:
textarea readonly(looks same as a regular textarea)

Upvotes: 21

Mehedi hasan
Mehedi hasan

Reputation: 111

You can write

$("textarea").attr("readonly", "readonly");

this will make readonly to all textarea fields.

Upvotes: 1

Doctor Rudolf
Doctor Rudolf

Reputation: 332

From Jquery 1.6 use

$("#mytxtarea").prop("disabled", true);

Visit http://api.jquery.com/prop/

Upvotes: 13

Gopi
Gopi

Reputation: 10293

Try this

$("#mytxtarea").attr("disabled", "disabled");

Upvotes: 8

Nick Craver
Nick Craver

Reputation: 630379

Include it in your selector (using a multiple/element selector), like this:

$('input[type="text"], textarea').attr('readonly','readonly');

You can test it here, if it's the only thing you're doing, there's no need for a .each(), you can just call .attr() on all matched elements.

Upvotes: 80

Related Questions