Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change HTML Textbox: Overwrite Instead of Insert as User Types

I am working on a service which will allow editing of text. To aid the user in the process, I'd like to allow the user to set a text field to overwrite mode, as is possible in Word, etc. How can the behaviour of an HTML text box be changed to overwrite instead of insert text as the user types?

For example, if the textbox had the text:

This is a trst.

The user could click between the r and the t, type a single e and the text would then be

This is a test.

with the cursor between the e and the s. I'm currently using jQuery, so methods using either that or pure javascript would be preferred. I would accept any reasonable solution, however.

like image 586
101100 Avatar asked May 25 '12 21:05

101100


People also ask

How do you change from insert to overwrite?

Turn on Overtype modeIn Word, choose File > Options. In the Word Options dialog box, choose Advanced. Under Editing options, do one of the following: To use Insert key to control Overtype mode, select the Use Insert key to control overtype check box.

How do you change overwrite text?

1. Press the "Ins" key to toggle overtype mode off. Depending on your keyboard model, this key may also be labeled "Insert." If you simply want to disable overtype mode but keep the ability to toggle it back on, you are done.

How do you change the input type in HTML?

To change the type of input it is (button to text, for example), use: myButton. type = "text"; //changes the input type from 'button' to 'text'. Another way to change or create an attribute is to use a method like element.

What is insert overwrite mode?

When the Update Processor is first entered, it is in overtype mode. This means any characters typed overwrite the characters on the screen. Insert mode is used to insert new text just in front of the text beginning at the cursor.


1 Answers

That's a bit of crazy but it seems to work somehow :)

Based on this answer and this answer this piece of code was created.

$("textarea").on("keypress", function(e) {
    var key = String.fromCharCode(e.which || e.charCode || e.keyCode);
    if (/[A-Za-z0-9 ]/.test(key)) {
        var text = this.innerHTML;
        var caret = getCaret(this);
        var output = text.substring(0, caret);
        this.innerHTML = output + key + text.substring(caret + 1);
        setCaretPosition(this, caret + 1);
        return false;
    }
    return true;
});​

DEMO: http://jsfiddle.net/aHSzC/

It works but now I have no time to fix a small bug I found.

  • If you press Backspace it seems to behave like a forward eraser.

Anyway, here is the code that can be improved. Feel free to edit my answer and do whatever you like.

like image 126
VisioN Avatar answered Sep 30 '22 04:09

VisioN