Johan Leino
Johan Leino

Reputation: 3533

Removing unwanted characters from textbox with JQuery

What I would like to get some input on is how to remove certain characters from a textbox (or textarea) with JQuery. I have the code in C# but I can´t seem to translate that to JQuery javascript. My problem is that I don´t know how to get the value from a textbox as a character array which I then can loop through and compare against a given set of unwanted characters. This is how "far" I have come in JQuery:

$("input[type=text], textarea").change(function() {

   // code here

});

This is my code in C#:

for (int i = 0; i < charArray.Length; i++)
{
    current = charArray[i];
    if ((current == 0x9) ||

        (current == 0xA) ||

        (current == 0xD) ||

        ((current >= 0x20) && (current <= 0xD7FF)) ||

        ((current >= 0xE000) && (current <= 0xFFFD)))
        _validXML.Append(current);
}

return _validXML.ToString().TrimEnd((char)32, (char)160) ;

UPDATE:

I went with a combination of some answers below (I will upvote them) and my final JQuery looks like this and works:

$(document).ready(function() {
    $(":text, textarea").change(function() {
        var text = "";
        var arr = $(this).val()
        $.each(arr, function(i) {
            var c = arr.charCodeAt(i);
            if ((c == 0x9) ||
                (c == 0xA) ||
                (c == 0xD) ||
                (c >= 0x20 && c <= 0xD7FF) ||
                (c >= 0xE000 && c <= 0xFFFD)) 
            {
                text += arr.charAt(i);
            }
        });
        $(this).val(text);
    });
});

Thanks all!

Upvotes: 4

Views: 11684

Answers (6)

razzed
razzed

Reputation: 2683

Textarea:

<textarea id="item" name="item" rows="5" cols="80">Some text in here</textarea>

jQuery code:

var text = $('#item').val();
var newtext = "";
for (var i = 0; i < text.length; i++) {
   var c = text.charCodeAt(i);
   if ((c == 0x9) || (c == 0xA) || (c == 0xD) || 
       (c >= 0x20 && c <= 0xD7FF) ||
       (c >= 0xE000 && c <= 0xFFFD)) {
       newtext += text[i];
   }
}
$('#item').val(newtext);

This has actually very little to do with jQuery, methinks, except to access the text data and set it again.

Upvotes: 1

Ron Savage
Ron Savage

Reputation: 11079

I prefer to stop the character from getting entered in the first place, using this type of javascript function (from my shady past):

each input control has something like this on it: onkeypress='checkKey(this,"a-zA-Z0-9","N","10");'

the function looks like:

   //****************************************************************************
   // Function: checkKey()
   //   Author: Ron Savage
   //     Date: 10-11-2004 
   //    
   // Description: This function tests reg exp syntax.
   //****************************************************************************
   function checkKey(textControl, reExpr, allCaps, maxlen)
    {
      popupMessage.hide();

      keyStr = String.fromCharCode(event.keyCode);
      textLength = textControl.value.length;

      if (allCaps == 'Y')
         {
         keyStr = keyStr.toUpperCase();
         event.keyCode = keyStr.charCodeAt(0);
         }

      if ( reExpr != '' )
         {
        reString = '[^' + reExpr + ']';
         re = new RegExp(reString, 'g');

         //alert('RE: ' + reString);

         result = keyStr.match(re);

         if (result)
            {
            beep();
            event.returnValue = false;
            showPopupMessage(textControl, result.toString() + ' not allowed!');
            }
         }

      if ( textLength > maxlen )
         {
            beep();
            event.returnValue = false;
            showPopupMessage(textControl, 'Max length [' + maxlen + '] exceeded!');
         }

      //alert('Key: ' + keyStr + ' code: ' + event.keyCode);
      }

Upvotes: -1

Jo&#227;o Marcus
Jo&#227;o Marcus

Reputation: 1608

Would't this be the case for regular expressions, like:

$("input[@type='text'], textarea").change(function() {
    this.value = this.value.replace(/[^\w\d]+/gim,"");
});

Upvotes: 6

nightingale2k1
nightingale2k1

Reputation: 10325

to get the value of textarea try:

$('input[type=textarea]').change(function(){
   var value = $(this).val(); 
   ...........
});

to remove unwanted character try this example .. i copy from the jquery documentation (jQuery.grep())

var arr = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
$("div").text(arr.join(", "));

arr = jQuery.grep(arr, function(n, i){
  return (n != 5 && i > 4);
});
$("p").text(arr.join(", "));

arr = jQuery.grep(arr, function (a) { return a != 9; });
$("span").text(arr.join(", "));

Upvotes: -1

Detect
Detect

Reputation: 2069

Use an event observer (onkeydown / onkeypress / onkeyup) on the input/textarea, get the key pressed, if the key is an unwanted character, stop the event from happening.

$("input[type=text], textarea").observe('keypress', function(e) {
 var keynum; 
 if(window.event)
 {
  keynum = e.keyCode
 }
 else if(e.which)
 {
  keynum = e.which
 }
 if(keynum == '13' || keynum == 'something else' || [...])
 {
  Event.stop(e);
 }
});

Upvotes: -1

Peter
Peter

Reputation: 6362

You can use the charCodeAt() method combined with the length property of strings to loop through the characters in the string.

Something like:

$("input[type=text], textarea").change(function() {
  var text = $(this).val()

  for(var i = 0; i < text.length; ++i) {
    var currentChar = text.charCodeAt(i);

    // Do something with it...
});

My initial version used charAt(), but since it looks like you're dealing with Unicode code points, charCodeAt() is more appropriate.

Upvotes: 1

Related Questions