Forum Moderators: open

Message Too Old, No Replies

IE, toggle readonly attribute on input not working

         

mcanada

8:35 pm on Sep 16, 2010 (gmt 0)

10+ Year Member



I have a need to display a text input box readonly, then when the user clicks on the input box, it will change to allow edit.

If I run this sample code in Firefox, it works fine, but in IE you have to click the input field twice before the readonly change takes for some reason.

<html>
<head>
<script>
function enable(desc) {
var d = document.getElementById(desc).readOnly=false;
}
function disable(desc) {
var d = document.getElementById(desc).readOnly=true;
}
</script>
</head>

<body>
<input type="text" name="0000" id="0000" value="[[FAX-DESC]]" size=60 onClick="javascript:enable('0000');" onChange="javascript:disable('0000');" readonly>
</body>
</html>

Any help would be appreciated.

Thank you
Mark

Fotiman

4:16 pm on Sep 17, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



A text input box that allows edit when a user clicks on it is not, by definition, readonly. It sounds as though your goal is to make the input's presentation look as though it's readonly? In which case, perhaps you should look at some CSS options. Also, you should use onfocus and onblur instead of onclick and onchange.

onfocus="enable(this);" onblur="disable(this);"

function enable(el) {
el.style.backgroundColor = "#fff";
el.style.fontStyle = "normal";
}
function disable(el) {
el.style.backgroundColor = "#ddd";
el.style.fontStyle = "italic";
}

Note, I just randomly chose to use fontStyle and backgroundColor, just to make it obvious that it changed when the input gets focus. Also, you need to set the initial state when the page loads.

Other notes:
1. you have an invalid id of "0000". ID's must start with a letter.
2. Event handlers don't need to be prefaced with "javascript:", so don't do it.
3. Use lowercase attributes (onclick vs. onClick).
4. Put scripts at the end of the document for better performance.
5. Always surround attribute values with quotes (size="60" vs. size=60)

Here's an updated example:

<html>
<head>
</head>
<body>
<input type="text" name="0000" id="x0000"
value="[[FAX-DESC]]" size="60"
onfocus="enable(this);" onblur="disable(this);">
<script>
function enable(el) {
el.style.backgroundColor = "#fff";
el.style.fontStyle = "normal";
}
function disable(el) {
el.style.backgroundColor = "#ddd";
el.style.fontStyle = "italic";
}
window.onload = function () {
disable(document.getElementById('x0000'));
};
</script>
</body>
</html>