Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

browser independent readonly?

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.

like image 562
JoelFan Avatar asked Apr 01 '11 01:04

JoelFan


People also ask

What is a readOnly attribute?

Read-only is a file attribute which only allows a user to view a file, restricting any writing to the file. Setting a file to “read-only” will still allow that file to be opened and read; however, changes such as deletions, overwrites, edits or name changes cannot be made.

How do you know if an element is readOnly?

Use the readOnly property to check if an element is read-only, e.g. if (element. readOnly) {} . The readOnly property returns true when the element is read-only, otherwise false is returned.


3 Answers

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

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

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

The readonly attribute is supported in all major browsers.

like image 52
bensiu Avatar answered Oct 05 '22 05:10

bensiu


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.

like image 30
sdleihssirhc Avatar answered Oct 05 '22 06:10

sdleihssirhc


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.

like image 38
kennebec Avatar answered Oct 05 '22 04:10

kennebec