views:

1488

answers:

6

Hey all!

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!

+1  A: 

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.

Peter
(+1)Thanks, got me on the right track...
Johan Leino
A: 

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);
 }
});
Detect
Very nice, but doesn't handle the case when text is pasted.
razzed
Yepp and that is what I´m trying to validate actually
Johan Leino
A: 

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(", "));
nightingale2k1
+1  A: 

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 += c;
   }
}
$('#item').val(newtext);

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

razzed
Even though this had the least to do with JQuery this is what solved my issue.
Johan Leino
A: 

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);
      }

Ron

Ron Savage
+4  A: 

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

$("input[@type='text'], textarea").change(function() {
    this.value = this.value.replace(/[^\w\d]+/gim,"");
});
João Marcus
You are missing a space in there ... but this is the best solution imho.
Evgeny
Probably faster and such but I want my code to make sense here so I´m not going with regex...at least not this time but thanks anyway.
Johan Leino