Javascrit keypress event does not work on mobile

Asked

Viewed 55 times

0

The Javascript code below, which serves to "bar" character > (asc 60) only works on desktop devices and not on mobile devices.

<textarea name='notes' id='ta' wrap='physical' cols='65' rows='8' style='width: 80%;' tabindex='14'></textarea>

<script>
var ta = document.getElementById("ta");
ta.addEventListener('keypress',
    function (e) {
       if (e.keyCode == 60) {
           alert('N\u00e3o use <');
           e.preventDefault();
       }
    }
);
</script>

2 answers

0

beforeinput
Inputevent.data

var ta = document.getElementById('ta');
ta.addEventListener('beforeinput', evt => {
    if (evt.inputType === 'insertText' && evt.data.charCodeAt(0) === 60) {
        alert('N\u00e3o use <');
        evt.preventDefault();
    }
});
<textarea name='notes' id='ta' wrap='hard' cols='65' rows='8' style='width: 80%;' tabindex='14' onpaste='return(false)'></textarea>

var ta = document.getElementById('ta');
ta.addEventListener(window.TextEvent && 'name' in window.TextEvent ? 'textInput' : 'keypress',
    function (evt) {
        if ((evt.which || evt.data.charCodeAt(0)) === 60) {
            alert('N\u00e3o use <');
            evt.preventDefault();
        }
    }, false);
<textarea name='notes' id='ta' wrap='hard' cols='65' rows='8' style='width: 80%;' tabindex='14' onpaste='return(false)'></textarea>

https://www.outsystems.com/blog/posts/create-input-mask-for-mobile/

-1

var ta = document.getElementById("ta");
ta.onkeydown = (e) => {
       const keyCode = e.which || e.keyCode;
       if (keyCode === 188 ) {
           alert('N\u00e3o use <');
           e.preventDefault();
       }
    }
<textarea name='notes' id='ta' wrap='physical' cols='65' rows='8' style='width: 80%;' tabindex='14'></textarea>

The problem is with event Keypress

This is because, certainly there is some problem with the event keypress in the Android browser (ie Chrome for mobile). Try replacing it with the event keydown, this usually works well.

  • Didn’t work, neither with desktop nor mobile

  • Can you please try now

  • @Did Roseli work? The rest is a matter of putting the right code for each character... https://keycode.info/

  • Look, I appreciate it, but it only worked on the desktop....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.