I’m trying to warning the user if he types a word that is not necessary in a textarea.
its just a little validation for some words.
i reach making something like this:
var words = "hello";
$("textarea").keyup(function(e){
var spliting = $("textarea").val().split(" ");
if(e.keyCode == 32){ // when the user hits space bar
if($.inArray(words, spliting) != -1){
$("span").css("background","red");
}else{
$("span").css("background","green");
}
}
});
is this the best way of doing this ?
and how can i migrate the variable words as a array, if i need to check more then one word?
To use an array, you will need to loop over each word in it and loop over each word in the split array. However, you can return on the first match:
I have removed the check for spaces. Even though it makes the function more efficient, you need to be wary of cases when someone goes back to correct spelling and ends up with an invalid word. The way you had it, those cases would never cause the flagged words to be found unless a space was typed later.
It would be advisable to call this function for
onchangeandblurevents as well, since typing is not the only way users enter input into form inputs.Here is the updated demo