How do I achieve this:-
When user types character like 'abcd'
and then '>'
(an invalid character for my application), I want to set the text back to 'abcd'
. Better if we can cancel the input itself as we do in winforms application. This should happen when user is typing and not on a click of button.
I want this to be applied on all text boxes in my web page. This will be easy if the solution is jQuery based. May be something which will start like this.
$("input[type='text']")
SOLUTION
I used both of the answer provided by @jAndy and @Iacopo (Sorry, couldn't mark as answer to both) as 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, '');
}
}
});
Though one issue still remained i.e. It doesn't allow user to select text in the textbox and this only happens on chrome, work fine on IE (for the first time :D), not tested on firefox. It would be glad if anyone can find solution for that or hope people at Google solves it :D.
UPDATE
I solved it by if (this.value != this.value.replace(/[<>]/g, ''))
check. Also updated solution.
Thanks again to all the answerers.