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.
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.
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.
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.
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.
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.
Anyway, here is the code that can be improved. Feel free to edit my answer and do whatever you like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With