How to use JavaScript to lock a key on the keyboard and display alert in the field on the recommended key?

4

How do I make a JavaScript to block the use of commas , within the field and at the same time also make an informed notification that only . is allowed and also verify that what the user entered is correct.

I do not have much JavaScript knowledge and I did not find much about it, the most I found was onKeyCode and had another that I forgot but did not get anything.

Example:  Current weight: 70.80

    
asked by anonymous 01.11.2017 / 20:10

2 answers

7

You can bind an event to the element of 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 the element you want to link

addEventListener binds a callback to a given event, in the example the linked event is keypress

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

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

    
01.11.2017 / 20:34
1

There is 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 a, from the keyboard. this site has the value of all: link

You can implement if you can not answer me here

    
01.11.2017 / 20:18