Allow only typing 123456 jquery

Asked

Viewed 63 times

0

I am studying Jquery and I came across a logic activity, I need to allow the user to only type the 123456 keys in the input.

html code:

 <h3>Teclado</h3>
    <span>Nome:</span>
    <input type="text" id="teclado" />
    <span id="resultadoTecla">Resultado do evento sobre o input</span>

jquery/javascript code

            $('#teclado').keyup((e) => {
                if(e.keyCode >= 97 && e.keyCode <= 102){                        
                    var number = $(e.target).val();
                    $(e.target).val(number);
                    console.log('log 1: ' + number);
                } else {

                } 
            })

I started the logic, but I don’t know how to prevent other values.

2 answers

2


If the idea is to allow only digits from 1 to 6 in the input, I would avoid this approach of checking the typed key, it has flaws like:

  • The user can click with the mouse and paste a text into the input, which would not pass the validation.

  • The user can use keyboard shortcuts, which may or may not be improperly validated.

  • The user can access the site by mobile, which produces keyCode different when inserting characters.

The safest solution would probably be to use a máscara. You can also format the value of input whenever it is changed, in order to delete all invalid characters, as in the example below:

$('#teclado').on('input', (evt) => {
    evt.target.value = evt.target.value.replace(/[^1-6]/g, '')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" id="teclado"/>

  • Thank you for your explanation, it helped me a lot, it was really something like this I was looking for, now I need to study a little more JS to know how to use replace correctly.

0

This can be achieved basically without the need for JS, you can use the attribute pattern:

<form action="#">
  <input pattern="[1-6]+" type="text" required>
  <input type="submit">
</form>


If you want the validation to occur "in real time", not only at the time of the Submit, could do:

window.document.addEventListener("input", function(e){
  if (!e.target instanceof HTMLInputElement || !e.target.form instanceof HTMLFormElement) {
    return
  }
   
  e.target.form.reportValidity()
}, true);
<form action="#">
  <input pattern="[1-6]+" title="Digite caracteres numéricos entre 1 e 6" type="text" required>
  <input type="submit">
</form>

The idea of this code is very simple, any change in any input will notify errors throughout the form.

  • +1 for pattern, but I don’t think that’s what he wants.

  • Thank you for the reply, I had never heard about Pattern, I am conducting a basic course of Jquery and the teacher did not comment on it, I will give a better study on the subject.

Browser other questions tagged

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