" in all input text windows using jquery How to achieve this: - When the user enters...">

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.

UPDATE
if (this.value != this.value.replace(/[<>]/g, '')). .

.

+1
3

"keyup" "blur" , : , .

,

$('input[type="text"]').keyup(purgeInvalidChars).blur(purgeInvalidChars)

function purgeInvalidChars()
{
   this.value = this.value.replace(/[<>]/g, ''); 
} 

, , , , .

, , cum grano salis: -)

+3

():

$(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) .

< >, , , . , .

: . preventDefault(), . stopPropagation()

+1
$('#textBox').keyup(function(e){
            var myText = $('#textBox').val(); 
            myText =  myText.replace(">", "");
            myText =  myText.replace("<", "");
            $('#textBox').val(myText);
        });

- -

keyup keypress

0
source

Source: https://habr.com/ru/post/1764859/


All Articles