Prevent insertion of special char on key press, but allow existing ones
I am facing some problems in preventing special chars in a textarea. My problem is how to describe below
I have an auto full textbox for multiple names and each name is comma separated (this is a requirement).
for example: Riki, jumjum, lima, Parth
My 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;
}
});
And my HTML:
<input type="text" name="Facilitator" id="facilitatorId" onkeyup="Validation(this, event)">
Validation(this, event)
the method only prevents numbers from being entered.
Now I am outputting the code in such a way that if the user tries to enter a special char (such as a comma) textbox
it will not accept the special char, but still it will not remove the existing special characters (the reason names are separated by commas)
Code Validation
:
function Validation(item, evt) {
var id = item.id;
var value = item.value.replace(/[0-9]/g, '')
$('#' + id).val(value);
}
source to share
Try jsFiddle .
It only allows you to write letters from z to A and Z on a tab.
$('#facilitatorId').keypress(function(e){
if(!((e.which >= 65 && e.which <= 90 ) ||
(e.which >= 97 && e.which <= 122 ) ||
e.which == 8)) {
e.preventDefault();
return false;
}
});
Above is an event trap.
EDIT: Updated code and script to prevent prevention backspace
in Firefox.
source to share