Changing the keypress
Here a simple example to replace ,
to .
using Vanilla JavaScript
// change ',' to '.'
document.getElementById('only_float').addEventListener('keypress', function(e){
if (e.key === ','){
// get old value
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
var oldValue = e.target.value;
// replace point and change input value
var newValue = oldValue.slice(0, start) + '.' + oldValue.slice(end)
e.target.value = newValue;
// replace cursor
e.target.selectionStart = e.target.selectionEnd = start + 1;
e.preventDefault();
}
})
<input type="text" id="only_float" />
You can't change the character or key associated with a key event, or fully simulate a key event. However, you can handle the keypress yourself and manually insert the character you want at the current insertion point/caret. I've provided code to do this in a number of places on Stack Overflow. For a contenteditable
element:
- Need to set cursor position to the end of a contentEditable div, issue with selection and range objects
Here's a jsFiddle example: http://www.jsfiddle.net/Ukkmu/4/
For an input:
Can I conditionally change the character entered into an input on keypress?
show different keyboard character from the typed one in google chrome
Cross-browser jsFiddle example: http://www.jsfiddle.net/EXH2k/6/
IE >= 9 and non-IE jsFiddle example: http://www.jsfiddle.net/EXH2k/7/
My solution example (change in input[type=text]
the character ','
to '.'
):
element.addEventListener('keydown', function (event) {
if(event.key === ','){
setTimeout(function() {
event.target.value += '.';
}, 4);
event.preventDefault();
};