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>
Related
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>
I am trying to create a simple web application. Like in Facebook chat when I enter "(Y)" it turns into the thumbs up icon. Similarly I am trying to do something like that with the following code. But it is not working for me. I am not expert with JavaScript. I need some help that what's wrong with the code?
And I made the code in a way that if i enter "y" it will return LIKE. I want to know how to show an icon after "y" input.
<html>
<head>
<title>Emogic</title>
</head>
<body>
<input type="text" id="input">
<input onclick="appear()" type="submit">
<p id="output"></p>
<script>
function appear(){
var value = document.getElementByid("input").value
var result = document.getElementById("output").innerHTML
if(value == "y"){
result = "LIKE"
}
else if(value == ""){
alert("You must enter a valid character.");
}
else{
alert("Character not recognised.");
}
}
</script>
</body>
</html>
There are a few issues/typo in your code :
it's document.getElementById(), with a capital I in Id.
result will be a string, containing the innerHTML of your element, but not a pointer to this innerHTML : when you then set result to an other value, it won't change the element's innerHTML as you expected. So you need to create a pointer to the element, and then set its innerHTML from the pointer.
The quick fix of your code would then be :
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
if (value == "y") {
output.innerHTML = "LIKE";
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="y">
<input onclick="appear()" type="submit">
<p id="output"></p>
But you'll find out that your user will have to enter exactly "y" and only "y" for it to work.
I think you should use instead String.replace() method with a regular expression to get all occurences of a pattern, i.e, for "(Y)" it could be
function appear() {
var value = document.getElementById("input").value;
var output = document.getElementById("output");
// The Regular Expression we're after
var reg = /\(Y\)/g;
// your replacement string
var replacement = 'LIKE';
// if we found one or more times the pattern
if (value.match(reg).length > 0) {
output.innerHTML = value.replace(reg, replacement);
} else if (value == "") {
alert("You must enter a valid character.");
} else {
alert("Character not recognised.");
}
}
<input type="text" id="input" value="I (Y) it (Y) that">
<input onclick="appear()" type="submit">
<p id="output"></p>
The converter is working fine, it looks for a match to the input and if it finds one, it converts it to the new value.
The problem I am running into is that I can output the new value with document.write(userInput);
But I dont know how to format or add html and text to the output. Help!
<!DOCTYPE html>
<html>
<body>
<h1>Value Converter</h1>
<input type="text" id="userInput"=>Enter the Value</input>
<button onclick="test()">Submit</button>
<script>
function test()
{
var userInput = document.getElementById("userInput").value;
if(userInput == "xxxx") {
userInput="yyyy";
}
else if(userInput == "yyyy") {
userInput="zzzz";
}
else {
userInput="Not Found";
}
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><b>Click here to Start Over</b>");
}
// Need to fix the "reset" to go back to restart the program
</script>
</body>
</html>
Change
document.write("<br /><br /><b> The equivalent value is: </b>") + (userInput) + ("< br /><br /><b>Click here to Start Over</b>");
For
document.write("<br /><br /><b> The equivalent value is: </b>" + userInput + "< br /><br /><b>Click here to Start Over</b>");
You should setup the html the way you want it to look, and then modify it using innerHTML or whatever DOM function/attributes instead of overwriting the page or having to reload it.
HTML
<h1>Value Converter</h1>
<input type="text" id="userInput" placeholder="Enter a value" />
<div>
<span>The equivalent value is: </span>
<span id="output">Enter a value and submit first</span>
</div>
<button onclick="test()">Submit</button>
JS
function test() {
var userInput = document.getElementById("userInput").value;
var converted = "";
switch(userInput){
case "someXXX":
//Do whatever code here
converted = "yyy";
break;
case "someYYY":
//Do whatever code here
converted = "zzz";
break;
default:
//Do whatever when all else fails
converted = "Not found";
break;
}
var output = document.getElementById("output");
output.innerHTML = converted;
}
Note that I changed your if statements to a switch/case
JSFiddle Demo
I'm trying to make multiple buttons that when clicked they add tags like <p></p> and <b></b> to a text-field. I have already figured out how to make it work like this:
<script>
function addtxt(input) {
var obj=document.getElementById(input)
obj.value+="<p></p>"
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body')">
but instead of having multiple scripts for every different button, I'd like to know if there is a way of the JS use the element value as obj.value. Is it possible?
EDIT: i found this other code online that's even better, how can i make this new code use the element value, is there any way?
function boldText(textAreaId, link)
{
var browser=navigator.appName
var b_version=navigator.appVersion
if (browser=="Microsoft Internet Explorer" && b_version>='4')
{
var str = document.selection.createRange().text;
document.getElementById(textAreaId).focus();
var sel = document.selection.createRange();
sel.text = "<b>" + str + "</b>";
return;
}
field = document.getElementById(textAreaId);
startPos = field.selectionStart;
endPos = field.selectionEnd;
before = field.value.substr(0, startPos);
selected = field.value.substr(field.selectionStart, (field.selectionEnd - field.selectionStart));
after = field.value.substr(field.selectionEnd, (field.value.length - field.selectionEnd));
field.value = before + "<b>" + selected + "</b>" + after;
}
You may pass this to your onclick handler, and then access it's value within your function:
<script>
function addtxt(input, button) {
var obj=document.getElementById(input);
obj.value+=button.value;
}
</script>
<input type="button" value="<p></p>" onclick="addtxt('body', this)">
<input type="button" value="<b></b>" onclick="addtxt('body', this)">
Here is an example with a specific div that receives the code javascript produces.
I don't recomend adding it to a div with id body, because that word is reserved for html structural elements, so I called the destination div "addHere".
Javascript
function addtxt(e) {
console.log(e)
var dest = document.getElementById("addHere");
dest.innerHTML = e.value;
}
HTML
<input type="button" value="<p>Text</p>" onclick="addtxt(this)">
<div id="addHere"></div>
fiddle here
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)