Prevent input of multiple characters, for example "<", ">" in all input text windows using jquery
How to achieve this: -
When the user enters a type character 'abcd', and then '>'(an invalid character for my application), I want to return the text to 'abcd'. It is better if we can cancel the input, as in a winforms application. This should happen when the user types, and not with the click of a button.
I want this to apply to all text fields on my web page. It will be easy if the solution is based on jQuery. Maybe it will be so.$("input[type='text']")
Solution
I used both answers provided by @jAndy and @Iacopo (Sorry, could not mark as an answer to both), as shown below.
$(document).ready(function() {
//makes sure that user cannot enter < or > sign in text boxes.
$("input:text").keyup(purgeInvalidChars)
.blur(purgeInvalidChars)
.bind('keypress', function(event) {
if (event.which === 62 || event.which === 60)
return (false);
});
function purgeInvalidChars() {
if (this.value != this.value.replace(/[<>]/g, '')) {
this.value = this.value.replace(/[<>]/g, '');
}
}
});
, , , IE ( : D), firefox. , - , Google : D.
UPDATEif (this.value != this.value.replace(/[<>]/g, '')). .
.
():
$(document).ready(function(){
$('input:text').bind('keypress', function(event){
if(event.which === 62 || event.which === 60)
return(false);
});
});
(keydown):
$(document).ready(function(){
$('input:text').bind('keydown', function(event){
if(event.which === 226)
return(false);
});
});
preventDefault stopPropagation . (false) .
< >, , , . , .