jQuery keyup() illegal characters
I have a field and want to prevent some illegal characters while showing the user as he types. How can I do this in follow example?
$('input').bind(开发者_Go百科"change keyup", function() {
var val = $(this).attr("value");
/*
if (val --contains-- '"') {
$(this).css("background", "red");
val = val.replace('"', "");
$(this).attr("value", val)
}
*/
$("p").html(val);
});
EDIT: I should put the illegal characters in an array
var vowels = new Array('"', "<", ">", "&");
Try to use a regular expression.
$('input').bind("change keyup", function() {
var val = $(this).val();
var regex = /["<>&]/g;
if (val.match(regex)) {
$(this).css("background", "red");
val = val.replace(regex, "");
$(this).val(val);
}
$("p").html(val);
});
And FYI: you can replace .attr("value",val)
with .val(val)
and .attr("value")
with .val()
UPDATE:
If you want to exclude more characters you can just put them into the regex. If you want to exclude an character that is used to control the regex you need to escape them with \
characters to control the regex are: []()/\+{}?*+.^$
Give this a try. No array, though.
$('input').bind("change keyup", function() {
var $th = $(this);
$th.val( $th.val().replace(/["<>&]/g, function(str) { return ''; } ) );
});
You may use the indexOf to determine if a string contains a certain char...
vowels = array('"', "<", ">", "&");
$('input').bind("change keyup", function()
{
var val = $(this).attr("value");
var illegal = '';
$(vowels).each(function()
{
if(val.indexOf(this)!=-1)
{
illegal= this;
break;
}
});
if(illegal != '')
{
$(this).css("background", "red");
val = val.replace(illegal, "");
$(this).attr("value", val)
}
});
精彩评论