gkrupp
gkrupp

Reputation: 428

Javascript input change

Is it possible to change the input value of the keyboard?

For example:

You press the a key on your keyboard but b will be typed into the input element, instead of a.

You type abc but in the input element will be def.

I tried to capture the keydown event and then fire a keydown event with CustomEvent / Event, but It doesn't work for me. The event capturing is fine but when I create an other keydown event with the new charCode or keyCode the 'new' character won't be typed into the input.

So, is it possible to write something into an input element to the position of the caret, without using value property or any other methods which handle or modify the whole content of the input. So just insert or paste a letter.

JS

function keydown(e) {
    e.preventDefault();

    var event = new Event('keydown');
    event.charCode = 65;
    element.dispatchEvent(event);
}

HTML

<input type="text" onkeydown="keydown(event)">

Probably, this is not possible in this way but I haven't any other idea so far...

Upvotes: 1

Views: 143

Answers (2)

gkrupp
gkrupp

Reputation: 428

I found another way to do this with document.execCommand():

document.querySelector("input")
.addEventListener("keypress", function (event) {
  event.preventDefault();
  document.execCommand('insertText', false, 'b');
})
<input>

Upvotes: 1

Sambi Reddy
Sambi Reddy

Reputation: 39

use the following code to get the cursor position when you type something. once you get the cursor position you can replace the character and set the text back to the text box. let me know you want code to put the cursor back to the location where it replaced the character.

<script type="text/javascript">
function getLocation(ctrl)
{
    var position = 0;

    if (document.selection) {

        ctrl.focus ();
        var sel = document.selection.createRange ();

        sel.moveStart ('character', -ctrl.value.length);

        position = Sel.text.length;
    }
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        position = ctrl.selectionStart;

    alert (position);
}

</script>
<input type="text" onkeyup="getLocation(this);"></input>

Upvotes: 0

Related Questions