Reputation: 377
I saw some code to allow only letters on textbox and I tried to use it in my code but it does not work and I don't know why. In jsfiddle it works perfectly.
I have this code:
$("Nombre").on("keydown", function(event) {
// Ignore controls such as backspace
var arr = [8, 16, 17, 20, 32, 35, 36, 37, 38, 39, 40, 45, 46];
// Allow letters
for (var i = 65; i <= 90; i++) {
arr.push(i);
}
if (jQuery.inArray(event.which, arr) === -1) {
event.preventDefault();
}
});
$("Nombre").on("input", function() {
var regexp = /[^a-zA-Z ]/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
}
});
<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>
Upvotes: 0
Views: 156
Reputation: 3512
Typo: $("Nombre")
should be $("#Nombre")
. Don't forget the #
before to let jQuery know that you want the element with the ID of Nombre.
$("#Nombre").on("keydown", function(event) {
// Ignore controls such as backspace
var arr = [8, 16, 17, 20, 32, 35, 36, 37, 38, 39, 40, 45, 46];
// Allow letters
for (var i = 65; i <= 90; i++) {
arr.push(i);
}
if (jQuery.inArray(event.which, arr) === -1) {
event.preventDefault();
}
});
$("#Nombre").on("input", function() {
var regexp = /[^a-zA-Z ]/g;
if ($(this).val().match(regexp)) {
$(this).val($(this).val().replace(regexp, ''));
}
});
<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>
Upvotes: 3