I have some jquery codes like this:
$("#inputMobile").keypress(function(event){
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
alert("Change your keyboard language to English");
});
$("#inputEmail").keypress(function(event){
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
alert("Change your keyboard language to English");
});
As you can see the main functions are same but the input id is different because I want to apply it into the both input fields.
So my question here is that, how can I refactor this code into one block of function and remove the extras ?
CodePudding user response:
The callback functions are identical, so just combine the selectors into one.
$("#inputMobile, #inputEmail").keypress(function(event){
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
alert("Change your keyboard language to English");
});
Note that .which
is deprecated. Better to use .key
or .code
to check which key was pressed. You could also condense the check into a concise regular expression.
$("#inputMobile, #inputEmail").keypress(function(event){
if (/[\da-z]/i.test(event.key)) {
return true;
}
alert("Change your keyboard language to English");
});
You also might consider using a proper modal instead of alert
, and that one could well press non-alphanumeric characters even on an English keyboard. A more precise message would be something like "Only alphanumeric characters are allowed."
CodePudding user response:
const handler = function(event) {
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
alert("Change your keyboard language to English");
};
["#inputMobile", "#inputEmail"].forEach(selector -> $(selector).keypress(handler));
CodePudding user response:
function handleKeypress(id){
$(`#${id}`).keypress(function(event){
var ew = event.which;
if(48 <= ew && ew <= 57)
return true;
if(65 <= ew && ew <= 90)
return true;
if(97 <= ew && ew <= 122)
return true;
alert("Change your keyboard language to English");
});
}
And now you can call it however times you want with handleKeypress("inputMobile")
and handleKeypress("inputEmail")
.
Hope it helps