使用JQuery从文本框中删除不需要的字符 [英] Removing unwanted characters from textbox with JQuery

查看:121
本文介绍了使用JQuery从文本框中删除不需要的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到的一些信息是如何使用JQuery从文本框(或textarea)中删除某些字符。我有C#中的代码,但我似乎无法将其转换为JQuery javascript。我的问题是我不知道如何从文本框中获取值作为字符数组,然后我可以循环并与给定的一组不需要的字符进行比较。
这就是我在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

});

这是我在C#中的代码:

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

更新:

我在下面给出了一些答案的组合(我将赞成它们),我的最终JQuery看起来像这样并起作用:

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

全部谢谢!

推荐答案

Textarea:

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

jQuery代码:

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

除了访问文本数据并设置它之外,这实际上与jQuery很少有关系。再次。

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

这篇关于使用JQuery从文本框中删除不需要的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆