dmo
dmo

Reputation: 4083

Make DOM element effectively read-only

I'm writing a .NET forms control to edit HTML using MSHTML. I am creating some custom elements and want to make them effectively read-only. I thought I could go about this by focusing on the entire element any time focus entered anywhere in that element but the HtmlElement.Focus() doesn't select the entire element and I don't seem to be able to capture entry of the cursor.

Another option would be to raise an event whenever the text of the element is changed (on KeyDown I expect) but I can't get that event to fire, either. Any ideas about why my expectations about event behavior is wrong or alternate suggestions for implementation?

Upvotes: 0

Views: 737

Answers (3)

Adrian
Adrian

Reputation: 11

This stops keydowns.

    document.onkeydown = function(e){
         e = e || window.event
        e.preventDefault();
        e.stopPropagation();
     }



Upvotes: 0

dmo
dmo

Reputation: 4083

I found that setting the attribute:

contentEditable=false

Resulted in the desired behavior.

Upvotes: 1

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31545

In case you are trying to apply readonly behavior to an User Input control, you can try using @readonly attribute of that control. Otherwise you could also add event listeners for appropriate UI events (keydown, mousedown) and prevent their default behavior (return false, or event.returnValue = false). As for custom events dispatch, you can indeed do that. Use event name that is known to IE. And another hint could be: register an onchange event handler and revert value of control to the value of defaultValue (property of any input controls).

Hope some of ideas will help.

Upvotes: 0

Related Questions