5

the event.preventDefault does not working in android as I know. so what is the best alternative way to prevent user typing special character in android on keydown event. note: the replace value solution when input event fired is good but in my situation doesn't solve the problem.

sina
  • 145
  • 1
  • 6

1 Answers1

0

In my case, the problem with replacing value on input event on Android, was with caret, that jumped to wrong position while typing.

I’ve solved it like this:

let input = document.getElementById("input")

function withoutForbiddenChars(str) {
    // change to your set of chars
    return str.replace(/[^\d]+/g, '')
}

function handleInput(event) {
    let charsBeforeCaret = input.value.slice(0, input.selectionStart)
    let charsAfterCaret = input.value.slice(input.selectionStart)
 
    charsBeforeCaret = withoutForbiddenChars(charsBeforeCaret)
    charsAfterCaret = withoutForbiddenChars(charsAfterCaret)
    
    input.value = charsBeforeCaret + charsAfterCaret
    
    let newCaretPos = charsBeforeCaret.length

    input.selectionStart = newCaretPos
    input.selectionEnd = newCaretPos
}

input.addEventListener('input', handleInput, false)

Demo: https://codepen.io/udovichenko/pen/vYWWjmR

Dmitry
  • 59
  • 3