Иногда возникает необходимость для ограничения ввода в поле каких-либо символов. Данные jQuery сниппеты позволяют ввод либо только цифр, либо только букв, для букв и цифр, для конкретных символов.
Ввод только цифр
// Ввод только цифр в тесте Акценты
$('#accento input').on('keydown', function(e){
if(e.key.length == 1 && e.key.match(/[^0-9'".]/)){
return false;
}
});2 вариант:
$(".class").keypress(function(event){
event = event || window.event;
if (event.charCode && event.charCode!=0 && event.charCode!=46 && (event.charCode < 48 || event.charCode > 57) )
return false;
});3 вартант:
$('body').on('click keypress', '.btn-input', function(key) {
$this = $(this);
$maxLen = 2;
// ограничение по длине
if ($this.val().length > $maxLen)
return false;
// ограничение по вводу нуля в начале
if ($this.val().length == 0 && key.charCode == 48)
return false;
// ограничение по символам
if (key.charCode < 48 || key.charCode > 57)
return false;
});Только буквы
$(function() {
$('#txtFirstName').keydown(function(e) {
if (e.shiftKey || e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});
});e.shiftKey, e.ctrlKey, e.altKey запрещают нажатие соответствующих клавиш (можно убрать это условие). Можно добавить конкретные символы: https://keycode.info/
Только английские в нижнем регистре:
$("#a").keypress(function(e) {
if(e.which < 97 /* a */ || e.which > 122 /* z */) {
e.preventDefault();
}
});2 вариант:
$('.alphaonly').bind('keyup blur',function(){
var node = $(this);
node.val(node.val().replace(/[^a-z]/g,'') ); }
);3 вариант:
$(".alpha-only").on("input", function(){
var regexp = /[^a-zA-Z]/g;
if($(this).val().match(regexp)){
$(this).val( $(this).val().replace(regexp,'') );
}
});4 вариант:
$(".alpha-only").on("keydown", function(event){
// Allow controls such as backspace, tab etc.
var arr = [8,9,16,17,20,35,36,37,38,39,40,45,46];
// Allow letters
for(var i = 65; i <= 90; i++){
arr.push(i);
}
// Prevent default if not in array
if(jQuery.inArray(event.which, arr) === -1){
event.preventDefault();
}
});Массив - белый список клавиш. Позволяет писать прописные и строчные буквы
Для букв, для цифр, для цифр и букв:
$("#test").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test1").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});
$("#test3").keypress(function(event){
var inputValue = event.charCode;
//alert(inputValue);
if(!((inputValue > 64 && inputValue < 91) || (inputValue > 96 && inputValue < 123)||(inputValue==32)||(inputValue > 47 && inputValue < 58) ||(inputValue==32) || (inputValue==0))){
event.preventDefault();
}
});Функция JQuery, чтобы разрешить только небольшие и капитальные буквы:
$('#a').keydown(function (e) {
if (e.ctrlKey || e.altKey) {
e.preventDefault();
} else {
var key = e.keyCode;
if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
e.preventDefault();
}
}
});Для букв с апострофами:
$('.alphaonly').on('keyup blur', function(){
if (this.value.match(/[^a-zA-Z àáèéìíòóùúÀÁÈÉÌÍÒÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z àáèéìíòóùúÀÁÈÉÌÍÒÓÚüÜ]/g, '');
}
});Если вам нужно привязать к динамическим элементам, код будет:
$(document).on('keyup blur', '.alphaonly', function(){
if (this.value.match(/[^a-zA-Z àáèéìíòóùúÀÁÈÉÌÍÒÓÚüÜ]/g))
{
this.value = this.value.replace(/[^a-zA-Z àáèéìíòóùúÀÁÈÉÌÍÒÓÚüÜ]/g, '');
}
});