Search for particular word using jQuery?
I have a script, which let's users submit e message. But I want to restrict some users from posting a particular world, and once that word is used, the form cannot be submitted (return false;) and an alert will be outputted.
So how would I d开发者_开发百科o a word check in jQuery?
Example:
1) Desired world to be blocked: Pizza
2) User puts this word in the textarea
3) User hits submit, but he used this word beside his other words so form doesn't submit
If jQuery cannot do this, but Javascript can, then I'd also welcome a Javascript solution.
Conceptually, when the submit button is pressed, you would get the contents of the textarea. You'd search it for the word pizza (one simple regular expression) and then if you found it, you would set a cookie that prohibits them from submitting for some period of time (you decide how long a time). Then, on the submit button, you'd check to see if the cookie exists and if it does, you'd prohibit the submit function. You can do this with either jQuery or pure javascript/browser - that's a personal preference.
Here's a little piece of the code:
var o = document.getElementById("myTextArea");
if (o.value.search(/\bPizza\b/i) != -1) {
alert("Pizza not allowed");
// set cookie preventing future access
}
Take the text string back that was placed in the form and perform an indexOf on it.
http://www.w3schools.com/jsref/jsref_indexof.asp
var str = "My pizza is better than yours. Dang right it's better than yours"
if str.indexOf("pizza") > -1
// do something cool
else
// do something different
Here's a full example:
<html>
<head>
<title>Example Form</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
function checkForm() {
var text = document.test_form.word.value;
if (text.indexOf("Pizza") > -1) {
alert("error");
return false;
}
return true;
}
</script>
</head>
<body>
<form action="blah.cgi" name="test_form" onSubmit="return checkForm()">
<input id="mytext" type="text" name="word" />
<input type="submit" value="Submit" />
</form>
<body>
</html>
Basically, what's happening here is that when the form is submitted, it calls the javascript function checkForm, which checks if the text contains the word Pizza (capitalized only at the moment), and if it does, it returns false, which prevents the submission of the form.
You should do the following
if you know all the keywords ahead, you can just store in them in a javascript object and write the logic.
1) You should store all the keywords already searched in some database or so
2) Using jquery' ajax and make a request to that database and check if it is already there.
http://api.jquery.com/jQuery.ajax/
3) Ajax has success call back , in that you can decide what you want to do
$.ajax({
url: "test.aspx",
success: function(){
// this tells you if it exists or not , the alert the user
}
});
精彩评论