0

I have a textbox and I want to get the value of the key pressed. I use jQuery to allow the user to insert only numbers and letters even if copy/paste is used. I'd like to get the letter or the number the user pressed.

$("#Nombre").on("keydown", function(event) {
  var regexp = /[^A-Za-z0-9]+/g;
  if ($(this).val().match(regexp)) {
    $(this).val($(this).val().replace(regexp, ''));
  } else {
    var Valor = $(this).val(); //get the value of keypressed here
  }
});

$("#Nombre").on("input", function() {
  var regexp = /[^A-Za-z0-9]+/g;
  if ($(this).val().match(regexp)) {
    $(this).val($(this).val().replace(regexp, ''));
  } else {
    var Valor = $(this).val(); //get the value of keypressed here
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="form-control" id="Nombre" Maxlength=43 name="txtNombre" required>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Errol Chaves Moya
  • 307
  • 2
  • 5
  • 20

1 Answers1

0

On keydown you can use String​.from​Char​Code() to get the character from event.keyCode. On input event you can get the last character from the value:

$("#Nombre").on("keydown", function(event) {
  var regexp = /[^A-Za-z0-9]+/g;
  if ($(this).val().match(regexp)) {
    $(this).val($(this).val().replace(regexp, ''));
  }
  else{
    var Valor = String.fromCharCode(event.keyCode)
    console.log(Valor);
  }
});

$("#Nombre").on("input", function() {
  var regexp = /[^A-Za-z0-9]+/g;
  if ($(this).val().match(regexp)) {
    $(this).val($(this).val().replace(regexp, ''));
  }
  else{
    var val = $(this).val();
    var Valor = val[val.length -1];    
    console.log(Valor);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="form-control" id="Nombre" Maxlength=43 name="txtNombre" required>
Mamun
  • 66,969
  • 9
  • 47
  • 59