我在阻止文本框中的特殊字符时遇到了一些问题。我的问题如下所述
我有一个自动完成多个名称的文本字段,每个名称用逗号分隔(这是要求)。
例如:Riki、jumjum、lima、Parth
我的Javascript:
$("#facilitatorId").autocomplete({
minLength: 1,
source: function(request, response) {
if(extractLast(request.term) != "" && extractLast(request.term).length >= 1) {
$.ajax({
cache: false,
type: "GET",
url: CompetencyWebApiUrl + "EventApi/GetAllUserNames?facilitatorName=" + extractLast(request.term),
dataType: "json",
timeout: 10000000,
success: function(data)
{
if (data != null && data.length > 0 && data[0].LogError == null)
{
var arryValue =[];
for (var i = 0; i < data.length; i++)
{
var facilitatorNames = {
text: data[i].FirstName + " " + data[i].LastName,
value : data[i].FirstName + " " + data[i].LastName
}
arryValue.push(facilitatorNames)
}
response(arryValue);
}
else
{
$(".ui-autocomplete").css("display", "none");
}
},
error: function (x, t, m)
{
if(t == "timeout")
{
$("#errorData").show();
$("#errorData").html("service timeout, Please run again");
}
else
{
$("#errorData").show();
$("#errorData").html("Rating service is unavailable, please try again after some time." + "" + "Error message:" + "" +t);
}
}
});
} //ends if
},
focus: function ()
{
// prevent value inserted on focus
return false;
},
select: function (event, ui)
{
//if its the first value then do not append comma and space before the value
if (this.value.trim().indexOf(' ') === -1)
{
var first = ui.item.text;
this.value = first + " ";
}
//else appends comma and space
else
{
var facilitator = $('#facilitatorId').val().trim();
var current = facilitator.substring(0, facilitator.lastIndexOf(" "));
current += ", " + ui.item.text;
this.value = current + " ";
}
return false;
}
});
我的 HTML 是:
<input type="text" name="Facilitator" id="facilitatorId" onkeyup="Validation(this, event)">
Validation(this, event)
方法仅防止输入数字。
现在我以这样的方式编写代码,如果用户尝试输入特殊字符(例如逗号),文本框
将不会接受特殊字符,但它仍然不会删除现有的特殊字符(因为名称以逗号分隔)
验证
的代码是:
function Validation(item, evt) {
var id = item.id;
var value = item.value.replace(/[0-9]/g, '')
$('#' + id).val(value);
}
最佳答案
试试这个 jsFiddle .
它只允许在输入中写入 a 到 z 和 A 到 Z 字符。
$('#facilitatorId').keypress(function(e){
if(!((e.which >= 65 && e.which <= 90 ) ||
(e.which >= 97 && e.which <= 122 ) ||
e.which == 8)) {
e.preventDefault();
return false;
}
});
上面是事件捕捉器。
编辑:更新了代码和 fiddle ,以停止阻止 Firefox 中的 backspace
。
关于javascript - 防止在按键时插入特殊字符,但允许现有的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26237599/