Reputation: 956
I have a text area that I would like to monitor for a predefined list of matching words or phrases on keyup. I can achieve this as follows but the problem I am having is displaying the matching word(s) and/or phrase(s) for the user. For example, if the user typed "test, test two", how would I return those matched items from the grep statement for display (or via some other method)? - i.e. having a div that is updated with something along the lines of "Please avoid using the following words and/or phrases: test1, test two".
function isBanned(array, name){
return $.grep(array, function(i){
return name.indexOf(i) >= 0;
}).length > 0;
}
var bannedInput = ['test1','test two'];
$('#eventText').keyup(function(){
var inputVal = $('#eventText').val();
var match = isBanned(bannedInput, inputVal.toLowerCase());
if(match){
alert("match found");
}
});
Upvotes: 1
Views: 553
Reputation: 1
Try
var input = $("#eventText"),
output = $("[for=eventText]"),
bannedInput = ["test1", "test two"];
input.on("keyup", function (e) {
var name = e.target.value.toLowerCase()
, match = $.grep(bannedInput, function (value) {
return new RegExp(value).test(name)
});
if (!!match.length) {
output.append(
"<br />Please avoid using the following words and/or phrases: "
+ "<span class=banned>\""
+ match.join(match.length === 1 ? " " : "\"<i>,</i> \"")
+ "\"</span>")
} else {
output.empty()
}
});
var input = $("#eventText"),
output = $("[for=eventText]"),
bannedInput = ["test1", "test two"];
input.on("keyup", function (e) {
var name = e.target.value.toLowerCase()
, match = $.grep(bannedInput, function (value) {
return new RegExp(value).test(name)
});
if (!!match.length) {
output.append(
"<br />Please avoid using the following words and/or phrases: "
+ "<span class=banned>\""
+ match.join(match.length === 1 ? " " : "\"<i>,</i> \"")
+ "\"</span>")
} else {
output.empty()
}
});
i {
color:rgb(0, 0, 0);
}
.banned {
color:rgb(0, 0, 255);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="eventText" /><output for="eventText"></output>
Upvotes: 1
Reputation: 2281
$.map
may help:
function isBanned(bannedWords, input){
return $.map(bannedWords, function(n, i){
return input.indexOf(n) >= 0 ? n : 0;
}
}
isBanned
will return an array that will have entries that are either a banned word, or 0. Then you can use $.grep
to get an array of banned words found in the input:
var filteredWords = isBanned(bannedInput, inputVal.toLowerCase());
var bannedWords = $.grep(filteredWords, function(n, i) {return n !== 0});
Upvotes: 0