accept numbers and character - in jquery

2
 $('input[name="test"]').bind('keydown', function(e) {
  var keyCode = (e.which) ? e.which : event.keyCode
    return !(keyCode > 31 && (keyCode < 48 || keyCode > 57));
});

This code validates that the data entry contains only numbers, but I need you to accept numbers and the character -

Thanks for your collaboration

    
asked by Alejandro 06.12.2018 в 22:39
source

2 answers

2

To accept the script (-) the Key Code is 189, therefore we will validate that you also take into account that key:

$('input[name="test"]').bind('keydown', function(e) {
  var keyCode = (e.which) ? e.which : event.keyCode
  return !(keyCode > 31 && (keyCode < 48 || keyCode > 57) && keyCode != 189);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="test" />
    
answered by 06.12.2018 / 23:39
source
1

Compare keyCode with: 189 , is the middle script code (" slash ") I with 109 which is the code for the minus sign (" NumpadSubtract ")

    
answered by 06.12.2018 в 23:00