shantaram shantaram - 7 months ago 10
Javascript Question

JQuery Validation - How do I detect '&' keyPress ( allow only '&' not '7', coz for both keycode is '55')

I want a validation which allows '&' keypress but not a numeric key '7', How do I do that.
Following is my code snippet ...

$(function(){
$('#idCategoryName').keydown(function(event){
var keyCode = event.keyCode;
var categoryName = $('#idCategoryName').val();
/* console.log("'"+ ( categoryName.slice(1) == " " ) +"' "+ categoryName.slice(1)); */
/* console.log(keyCode); */
if( keyCode == 32 ) {
if( ( categoryName.slice(-1) == " ") )
event.preventDefault();
if( event.target.selectionStart === 0)
return false;
}
if( keyCode == 55 )
if( ( categoryName.slice(-1) == "&") )
event.preventDefault();
if( keyCode == 191 )
if( ( categoryName.slice(-1) == "/" ) )
event.preventDefault();
return ( ( keyCode >= 65 && keyCode <= 90 ) || keyCode == 8 || keyCode == 9 ||
keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 ||
keyCode == 32 || keyCode == 13 || keyCode == 46 || keyCode == 55 ||
keyCode == 191 );
});
});


This code allows '7' to be entered , and I dont want any numeric value to my inputbox , code improvemet, welcome...

My Updated, working snippet ...

$(function(){
$('#idCategoryName').keydown(function(event){
var keyCode = event.keyCode;
var categoryName = $('#idCategoryName').val();
/* console.log("'"+ ( categoryName.slice(1) == " " ) +"' "+ categoryName.slice(1)); */
/* console.log(keyCode); */
if( keyCode == 32 ) {
if( ( categoryName.slice(-1) == " ") )
event.preventDefault();
if( event.target.selectionStart === 0)
return false;
}
**Changed Here**
if( event.shiftKey ) {
if( ( categoryName.slice(-1) == "&") )
event.preventDefault();
if( keyCode == 55 )
return true;
}
if( keyCode == 191 )
if( ( categoryName.slice(-1) == "/" ) )
event.preventDefault();
return ( ( keyCode >= 65 && keyCode <= 90 ) || keyCode == 8 || keyCode == 9 ||
keyCode == 37 || keyCode == 38 || keyCode == 39 || keyCode == 40 ||
keyCode == 32 || keyCode == 13 || keyCode == 46 || keyCode == 191 );
});
});

Answer

You need to detect the shift key too. Then put that in an if statement.

based on your code

Example:

if(event.shiftKey == true && keyCode == 55) {
    alert("Shift + 7 (&) are pressed!");
}

The keyCode for shift is 16.

Example on fiddle: http://jsfiddle.net/C0dekid/dprx94j7/

Comments