How to use Javascript to lock a keyboard key and display alert in the field about the recommended key?

Asked

Viewed 1,472 times

4

How do I make a Javascript to block comma usage , within the field and at the same time also make an informed notification that point only . is allowed and also check if what the user has typed is correct.

I don’t have much knowledge in Javascript and I didn’t think much about it, the most I could find was onKeyCode and there was another that I forgot but got nothing.

Example: current weight: 70.80

2 answers

7


You can link an event in the input

Example:

document.querySelector('input').addEventListener('keypress', function(evt) {
    if (evt.key == ',') {
        evt.preventDefault()
        alert('Tecla inválida');
    }
});
<input type="text">

document.querySelector('input') will return you the element you want to link

addEventListener links a callback for a given event, in the example the linked event is keypress

function(evt){ console.log(evt.key); } is the callback, the action that will be executed when the event occurs.

You can call the method preventDefault() to prevent the standard event action

  • 1

    Maybe add evt.preventDefault() within the if to block, in fact, the use of the comma?

  • @Andersoncarloswoss, edited, had forgotten this detail :)

1

Have a jQuery event that is called keypress, by parameter you pass a function with an if if the comma key has been pressed ie :

Ex:

$(document).keypress(function(e) {
    if(e.which == 188) {
        alert('You pressed a virgula!');
    }
});

188 is the , of the keyboard. this site has the value of all: http://www.javascripter.net/faq/keycodes.htm

See if you can implement if you can’t answer me here

  • 1

    There is a very nice site, where you press the key and it shows the corresponding code, see keycode.info

Browser other questions tagged

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