jQuery keyup() illegal characters

2019-03-02 17:19发布

问题:

I have a field and want to prevent some illegal characters while showing the user as he types. How can I do this in follow example?

  $('input').bind("change keyup", function() {
   var val = $(this).attr("value");
   /*
   if (val --contains-- '"') {
    $(this).css("background", "red");
           val = val.replace('"', "");
              $(this).attr("value", val)
   }
   */
   $("p").html(val);
  });

EDIT: I should put the illegal characters in an array

var vowels = new Array('"', "<", ">", "&");

回答1:

Try to use a regular expression.

$('input').bind("change keyup", function() {
 var val = $(this).val();
 var regex = /["<>&]/g;
 if (val.match(regex)) {
   $(this).css("background", "red");
   val = val.replace(regex, "");
   $(this).val(val);
 }
 $("p").html(val);
});

And FYI: you can replace .attr("value",val) with .val(val) and .attr("value") with .val()

UPDATE:

If you want to exclude more characters you can just put them into the regex. If you want to exclude an character that is used to control the regex you need to escape them with \ characters to control the regex are: []()/\+{}?*+.^$



回答2:

Give this a try. No array, though.

    $('input').bind("change keyup", function() {
        var $th = $(this);
        $th.val( $th.val().replace(/["<>&]/g, function(str) {  return ''; } ) );
    }); 


回答3:

You may use the indexOf to determine if a string contains a certain char...

vowels = array('"', "<", ">", "&");

$('input').bind("change keyup", function()
{
   var val = $(this).attr("value");
   var illegal = '';       
   $(vowels).each(function()
   {
      if(val.indexOf(this)!=-1)
      {
          illegal= this;
          break;
      }
   });
   if(illegal != '') 
   {
       $(this).css("background", "red");
       val = val.replace(illegal, "");
       $(this).attr("value", val)
   }
});


标签: jquery key