admin管理员组

文章数量:1291052

Is there a way in HTML, JavaScript or jQuery to make an input element "readonly", i.e.

  • the user can read it
  • the user can copy its content to the clipboard
  • the user can't change it

that will work in all browsers? I know there is a "readonly" attribute but it's not supported in all browsers.

I'm not asking about security aspects, just user experience.

Is there a way in HTML, JavaScript or jQuery to make an input element "readonly", i.e.

  • the user can read it
  • the user can copy its content to the clipboard
  • the user can't change it

that will work in all browsers? I know there is a "readonly" attribute but it's not supported in all browsers.

I'm not asking about security aspects, just user experience.

Share Improve this question asked Apr 1, 2011 at 1:45 JoelFanJoelFan 38.7k38 gold badges141 silver badges214 bronze badges 9
  • 1 +1 just to see those those pretty unicorns – Shekhar_Pro Commented Apr 1, 2011 at 1:47
  • @Slurpie It is supported in all current browsers. What you need is a fix for IE8 and below... (let's say it as it is) – Šime Vidas Commented Apr 1, 2011 at 1:49
  • I want it to work in all browsers in mon use – JoelFan Commented Apr 1, 2011 at 1:50
  • Why "not supported"? MSDN says it's defined in HTML 4 and DOM level 1 -- don't they support it by now? (disclaimer: I 'm just asking, I don't know) – Jon Commented Apr 1, 2011 at 1:51
  • 1 @Slurpie google./images?q=unicorn – Šime Vidas Commented Apr 1, 2011 at 1:59
 |  Show 4 more ments

3 Answers 3

Reset to default 6

if you using jQuery (as you put in tag) it cross-browser:

$(...your input ...).attr('readonly','readonly'); 

edit: from http://www.w3schools./tags/att_input_readonly.asp

The readonly attribute is supported in all major browsers.

One way is to fake it:

<p class="fake_input">The readonly Value</p>
<input type="hidden" name="real_input" value="The readonly Value" />

And if you wanted it to look like a disabled input box, you could style it and stuff.

Just remember that people can change hidden inputs willy nilly.

Although the readOnly attribute is case insensitive in html it must be written 'readOnly' in js. It works when directly assigned in all browsers from and including IE6, but the way you assign it can be browser specific.

element.setAttribute('readOnly','readOnly') does not work in older browsers, but element.readOnly='readOnly' (or any truthy value') works x-browser.

本文标签: javascriptbrowser independent readonlyStack Overflow