JavaScript avoid bad words in textarea by using an alert box? - javascript

I have to make a script which can check my textarea if there are any bad words in there. Once the users leaves the textarea their should be alert box appearing. After that the inputted text in the area should be deleted.
I need JavaScript solutions (no jQuery please).
<!DOCTYPE html>
<html>
<head>
<title>RIC</title>
</head>
<body>
<textarea name="ric" id="textarea">
</textarea>
<script>
my_textarea = document.getElementById('textarea');
if (/\b(?=\w)(asshole|fucking)\b(?!\w)/i.test(my_textarea.value)) {
alert("Hey no bad words here!");
} else {
// Okay move on!
}
</script>
</body>
</html>

Here's what you can do. First create a function which will check for invalid words and clear the textarea:
function filterTextarea() {
var textarea = document.getElementById('textarea');
var matches = textarea.value.match(<THE REGEX FOR THE WORDS YOU WANT TO FILTER>);
if (matches) {
alert('Hey, no bad words!');
textarea.value = '';
return;
}
// Other stuff.
}
Then attach an event listener to the textarea, which will check it every time a key is pressed and pass your function as a callback.
document.getElementById('textarea').addEventListener('keyup', filterTextarea, false);

This code should work. It will also censor the words by replacing them with a group of asterisk characters.
<!DOCTYPE html>
<html>
<head>
<title>RIC</title>
</head>
<body>
<textarea name="ric" id="textarea" onblur="checkWords()"></textarea>
<script>
function checkWords() {
var my_textarea = document.getElementById('textarea').value;
var pattern = /fox|dog/ig;
if (my_textarea.match(pattern)) {
alert("Hey no bad words here!");
my_textarea = my_textarea.replace(pattern, "****" );
document.getElementById('textarea').value = my_textarea;
}
}
</script>
</body>
</html>

The reason your function does not get called (well it does get called, once at page load) is because there is no event handler to check when the user leaves the text area. You can either use onChange or onBlur they both trigger when the user leaves but onChange will only trigger when the content has actually been changed.
Try changing your code to this:
<textarea name="ric" id="textarea" onBlur="check()">
</textarea>
<script>
var check = function(){
my_textarea = document.getElementById('textarea');
if (/\b(?=\w)(asshole|fucking)\b(?!\w)/i.test(my_textarea.value)) {
alert("Hey no bad words here!");
my_textarea.value = "";
} else {
// Okay move on!
}}
</script>
As for the checking on bad words, as stated by others you can loop an array of 'bad words' with <text>.indexOf(<bad word>) and check if the index is found or not. There might be a 'nicer' way using regex but can't help with that

Here goes my code,Please do populate the badword array with your bad words and this code must oppose bad words ,it will.!!!
<div>
<textarea name="ric" id="txtArea" onkeyup="badWordChecker()" onblur="nothingTyped()"> </textarea>
</div>
<script>
function nothingTyped() {
var badWordTextBoxLength = document.getElementById('txtArea').value.length;
if (badWordTextBoxLength == 0) {
alert("YOu cannot leave easily!!!Please type something ");
document.getElementById('txtArea').focus();
return false;
}
}
function badWordChecker() {
//create an array of bad words
var badwords = ["f***", "a****", "f***"];
var badWordTextBox = document.getElementById('txtArea');
var badWordTextBoxValue = badWordTextBox.innerText;
var backgroundcolor = "white";
function isTheWordBad(value, index, array) {
if (value == badWordTextBoxValue) {
alert("hey!No badwords");
badWordTextBox.textContent = "";
return true;
}
else {
return false;
}
}
var result = badwords.filter(isTheWordBad);
}
</script>
</body>

Related

word does not display in Chrome until you end the shuffle [duplicate]

This question already has answers here:
While True loop prevents page from loading
(5 answers)
Closed 24 days ago.
In this program below, the variable word does not display in any browser every time you shuffle.
let word = prompt("Enter a word:");
while (true) {
let scramble = scrambleWord(word);
displayWord(scramble);
let again = prompt("Scramble again? (y/n)");
if (again === "n") {
break;
}
}
function scrambleWord(word) {
word = word.split("").sort(() => Math.random() - 0.5).join("");
return word;
}
function displayWord(scramble) {
let displayArea = document.getElementById("display-area");
displayArea.innerHTML = scramble;
}
<!DOCTYPE html>
<html>
<body>
<div id="display-area"></div>
</body>
</html>
Any ideas what is wrong with it?
Regards,
Lee
the word should appear each time it's shuffled.
To do exactly what you want it´s necessary to put the prompt function inside a promisse and use a setTimeout() function to wait a minimum time to let the browse display the tag in the page.
like this:
function displayWord() {
getPrompt().then((word) => {
if (word !== 'n') {
document.getElementById('display-area').textContent = word
.split('')
.sort(() => Math.random() - 0.5)
.join('');
displayWord();
}
});
}
function getPrompt() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(prompt('Enter a word (enter \'n\' to exit):'));
}, 30);
});
}
displayWord();
<div id="display-area"></div>
The problem is that the prompt() method blocks the JavaScript execution and does not allow the webpage to update and display the id="display-area" div element. As a result the code you provided wont appear each time it's shuffled.
Instead, what you can do is add a button instead of a prompt and add an Event Listener.
Below, I edited your code to show how you can achieve your desired output using button and Event Listener instead of prompt.
let scrambleButton = document.getElementById("scramble-button");
scrambleButton.addEventListener("click", scrambleWord);
function scrambleWord() {
let word = document.getElementById("word-input").value;
let scramble = word.split("").sort(() => Math.random() - 0.5).join("");
let displayArea = document.getElementById("display-area");
displayArea.innerHTML = "Original Word: " + word + "<br>Scrambled Word: " + scramble;
}
<div id="display-area"></div>
<input type="text" id="word-input">
<button id="scramble-button">Scramble</button>
Explanation: The word input id input element accepts data from the user. Whenever the scramble-button id button element is clicked, it will trigger the Event Listener calling the scrambleWord() and shuffle the word. I hope this will help you.
I'm not sure but
I think this might be due to the script loading before your DOM tree is finished loading. you can fix this by adding the defer tag after your script
Try it out and let me know if it worked :)
src = https://javascript.info/script-async-defer
As explained by #JohnnyMopp in the first comment, the loop is blocking the renderer from updating. But if you don't have to use prompt for this assignment then you can implement the main functionality using a form with a text field, where the user enter the word, and a submit button that will scramble the word when you click on it:
document.getElementById("word-form").addEventListener("submit", function(e) {
e.preventDefault();
let word = document.getElementById("word").value;
let scramble = scrambleWord(word);
displayWord(scramble);
});
/*let word = prompt("Enter a word:");
while (true) {
let scramble = scrambleWord(word);
displayWord(scramble);
let again = prompt("Scramble again? (y/n)");
if (again === "n") {
break;
}
}*/
function scrambleWord(word) {
word = word.split("").sort(() => Math.random() - 0.5).join("");
return word;
}
function displayWord(scramble) {
let displayArea = document.getElementById("display-area");
displayArea.innerHTML = scramble;
}
<!DOCTYPE html>
<html>
<body>
<form id="word-form">
<label>
Enter a word:
<input type="text" name="word" id="word" />
</label>
<input type="submit" name="submit" id="submit" value="submit" />
</form>
<div id="display-area"></div>
</body>
</html>

Check if TextArea/TextBox contains a certain String

Given textarea is a textarea element with id 'textareabox', how can I check if it contains a string within it?
var textarea = document.getElementById('textareabox');
var word = something;
if (!textarea.contains(word))
{
textarea.value += word;
}
You can use .value, as:
var textarea = document.getElementById('textareabox');
var word = 'something';
var textValue=textarea.value; //-> don't use .innerHTML since there is no HTML in a textarea element
if (textValue.indexOf(word)!=-1)
{
alert('found')
}
You could do something like this:
var textarea = document.getElementById('textareabox').value;
if (texarea.match(word) != null) {
// do some stuff
}
A better regex than what I did but I don't know regex all that well (forgive me regex ignorance).
body {
background-color: red;
}
<html>
<h1>#mywebsite</h1>
<body>1+1=2?(yes <strong>or</strong> no)</body>
<input type="text" id="text" placeholder="text here"></input>
<button type="button" id="u" onclick="run()">submit</button>
<script type="text/javascript">
var a = 1;
function run() {
if (document.getElementById("text").value.includes("yes")) {
alert("correct!");
/*if the textbox includes "yes" it will say you got it right; basically whatever the input your user puts into the textbox it will test if the users sentence contains "yes" it alerts "correct!" into html if its wrong well it alerts "Try again!" the thing is, no matter what, if yes is in the sentance it will still say its correct.*/
/*if the snippet will not work use a different website to put code on */
document.body.innerHTML += "<li>attempt #" + a + ": correct";
a++
}
else {
alert("try again!")
document.body.innerHTML += "<li>attempt #" + a + ": try again";
a++
}
}
</script>

Erasing value in textarea if special text is typed in

I want to erase the value of textarea if <br> is typed in. Currently I only have the code below. I know the question sounds quite strange but I am trying to use the code with a type effect.
function eraseText() {
document.getElementById("textarea1").value = "";
}
<textarea id="textarea"> text <br /> text </textarea>
<script>
document.getElementById('textarea').onkeyup = function() {
if (/<br \/>/m.test(this.value))
this.value = '';
};
</script>
Example
How about:
document.getElementById("textarea1").onkeyup = function () {
if (document.getElementById("textarea1").indexOf("<br>") !== -1) {
document.getElementById("textarea1").value = "";
}
}

Javascript onkeypress event fires but input text value is incorrect

I'm writing a simple javascript form that checks the input value against the value "blue". Now if you enter "blue", it says it's incorrect, but then if add any additional character, it says correct. It seems like there's a one-character delay, so when I enter "blue" it's only getting "blu". Here is the code:
<html>
<head>
<title>Favorite Color</title>
</head>
<body>
<h1>Quiz Time</h1>
<h2>What is your favorite color?</h2>
<p>Your Answer: <input type="text" id="txtinput" /></p>
<p id="message"></p>
<script type = "text/javascript">
function init() {
var inp = document.getElementById("txtinput");
inp.onkeypress=checkAnswer;
checkAnswer();
}
onload = init;
function checkAnswer() {
var text = document.getElementById("txtinput");
var msg = document.getElementById("message");
var sol = "blue";
var ans = text.value;
ans = ans.toLowerCase();
if (ans.length <=0) {
msg.innerHTML="<span style=\"color:blue;\">Enter Something.</span>";
}
else if (ans == sol) {
msg.innerHTML="<span style=\"color:green;\">Correct!</span>";
} else {
msg.innerHTML="<span style=\"color:red;\">Wrong!</span>";
}
}
</script>
</body>
</html>
Change the event to onkeyup instead of onkeypress
inp.onkeyup=checkAnswer;
Use the HTML5 input event with a fallback to the propertychange event in IE < 9. I've written about this many times on SO; here are two examples:
jQuery keyboard events
Catch only keypresses that change input?

Javascript form validation

I'm trying to have two functions checking each form input, one for onchange() and the other for onkeypress(); my reason for this would be to show if the input was valid once you leave the input field using onchange() or onblur(), and the I also wanted to check if the input field was ever empty, to remove the message indicating that bad input was entered using onkeypress() so that it would update without having to leave the field (if the user were to delete what they had in response to the warning message.)
It simply isn't working the way I intended, so I was wondering if there was something obviously wrong.
My code looks like this:
<form action="database.php" method = post>
Username
<input type='text' id='un' onchange="checkname()" onkeypress="checkempty(id)" />
<div id="name"></div><br>
.....
</form>
And the Javascript:
<script type="text/javascript">
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (name.search(pattern) == -1) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}
function checkempty(id) {
var temp = document.getElementById(id).value;
if (!temp) {
document.getElementById("name").innerHTML = '';
}
}
</script>
Per your clarification in the comments, I would suggest using the onkeyup event instead of onkeypress (onkeypress only tracks keys that generate characters - backspace does not). Switching events will allow you to validate when the user presses backspace.
Here's a working fiddle.
Edit:
See this SO question for further clarification: Why doesn't keypress handle the delete key and the backspace key
This function should below should check for empty field;
function checkempty(id) {
var temp = document.getElementById(id).value;
if(temp === '' || temp.length ===0){
alert('The field is empty');
return;
}
}
//This should work for check name function
function checkname() {
var name = document.getElementById("un").value;
var pattern = /^[A-Z][A-Za-z0-9]{3,19}$/;
if (!name.test(pattern)) {
document.getElementById("name").innerHTML = "wrong";
}
else {
document.getElementById("name").innerHTML = "right!";
}
}

Categories