Comparing two functions in JavaScript - javascript

I'm developing a mobile app for my wife's 1st grade class so they can practice sight words. I'm a novice to JavaScript but I was able to pull off my first objective which was to take a JavaScript array and extract a random word from it. My second objective is to have the user type in the word that they see, click a button and have the word they entered be compared to the random word. I attempted to do this with a second function but it did not do it. I don't get any errors in the console so I'm a bit lost on how to get this working. Any help would be greatly appreciated by me and a great group of 1st graders. Here is the code that I have so far.
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;
var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerHTML = showWord;
}
function checkSpelling(result) {
document.getElementById("result").innerHTML=checkWord;
}
</script>
</body>
</html>

You mixed up value and innerHTML.
value is used for input and textarea elements and innerHTML is for almost other element
This code will work for you:
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="myFunction()">New Word</button>
<button onclick="checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn");
var aWord = document.getElementById("aWord");
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerHTML = showWord;
}
function checkSpelling(result) {
var checkWord = (yourTurn.value == aWord.innerHTML)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
</script>
</body>
</html>
See live code here: http://jsbin.com/ubofus/1/edit

The problem is that you're evaluating checkWord only once, when the browser runs your JavaScript.
So, the checkWord variable is always "Nice Job!".
Another problem is that you're using value on a p element. p elements don't have such properties.
And the last issue is that you're comparing 2 values with ==. It isn't enough, because "" == undefined, undefined being what value on a p element returns.
To sum it up, you want to evaluate checkWord every time, and you want to compare apples to apples. Which would lead to this kind of code:
function checkSpelling(result) {
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").innerHTML;
var checkWord = (yourTurn == aWord)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
One last thing: I'm using innerHTML there, but it's bad. You don't want HTML, you want text. It'd be better to use textContent, or innerText on older IE (6, 7, 8). If you don't want to worry about this kind of cross-browser mess, use a library to abstract away all of this.

Okay I got it working for you. I have it in a JS Fiddle: http://jsfiddle.net/D6ERg/4/
<!DOCTYPE html>
<html>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourTurn">
<button onclick="window.wordApp.newWord()">New Word</button>
<button onclick="window.wordApp.checkSpelling()">Check My Spelling</button>
<p id="result"></p>
<script>
window.wordApp = (function() {
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var aWord = document.getElementById("aWord");
return {
newWord : function() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
aWord.innerText = showWord;
},
checkSpelling : function() {
var yourTurn = document.getElementById("yourTurn").value;
var checkWord = (yourTurn == aWord.innerText)?"Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML=checkWord;
}
}
})();
</script>
</body>
</html>
You had a lot of problems. Things that update need to be in functions. I also removed the global variables for best practices and easier debugging.
The (function() {})(); design pattern may be too advanced for you now, but you can look up closures or watch the video Paul Irish talking about how jQuery works. You will learn a lot. Also the book Javascript The Good Parts by Crockford is a book that I wish I read when I started.

Cleaned up your code a little, also fiddled: http://jsfiddle.net/3Ptzu/
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
var yourTurn = document.getElementById("yourTurn").value;
var aWord = document.getElementById("aWord").value;
function myFunction() {
var showWord = sightWord[Math.floor((Math.random()*10)+1)];
document.getElementById("aWord").innerHTML = showWord;
}
function checkSpelling(result) {
var challengeWord = document.getElementById("aWord").innerHTML;
var checkWord = document.getElementById("yourTurn").value;
var result = (challengeWord == checkWord) ? "Nice Job!":"So close! Try again!";
document.getElementById("result").innerHTML = result;
}

This one avoids inline scripts:
HTML
<h1>Practice Spelling Test</h1>
<p id="aWord"></p>
<input id="yourWord">
<button id="newWord">New Word</button>
<button id="spellCheck">Check My Spelling</button>
<p id="result"></p>
JS
//list of words
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"];
//variable containing the current word
var currentWord;
//reference to the "congrats" box
var result = document.getElementById('result');
//reference to the input
var yourWord = document.getElementById('yourWord');
//when new word is clicked
document.getElementById('newWord').onclick = function () {
//get a new word from the list
aWord.innerHTML = currentWord = sightWord[Math.floor((Math.random() * 10) + 1)];
}
//when spell check is clicked
document.getElementById('spellCheck').onclick = function () {
//compare and announce accordingly
var check = (yourWord.value === currentWord) ? "Nice Job!" : "So close! Try again!";
result.innerHTML = check;
}

There is a difference between innerHTML and value; the value is actually an attribute of the input tag. Here is a cross browser way to handle this, without any inline JavaScript:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<title>Practice Spelling Test</title>
<meta charset="UTF-8" />
<script>
(function(d){
var modern = (d.addEventListener) ? true : false, load = function(fn){
if(modern) {
d.addEventListener("DOMContentLoaded", fn, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
fn();
}
});
}
}, event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, init = function(){
var sightWord = ["hoof", "hook", "shook", "hood", "wood", "took", "book", "good", "food", "mood", "look"], newWordButton = d.getElementById("newWord"), checkSpellButton = d.getElementById("checkSpell"), aWord = d.getElementById("aWord"), yourTurn = d.getElementById("yourTurn"), result = d.getElementById("result"), lastWord = null, newWord = function(){
var count = Math.floor(Math.random()*(sightWord.length - 1));
if(count == lastWord) {
newWord();
} else {
aWord.innerHTML = sightWord[count];
lastWord = count;
}
}, checkSpell = function(){
var curr = aWord.innerHTML, input = yourTurn.value;
if(curr && input) {
result.innerHTML = (curr == input) ? "Nice Job!" : "So close! Try again!";
}
};
event(newWordButton, "click", newWord);
event(checkSpellButton, "click", checkSpell);
};
load(init);
})(document);
</script>
</head>
<body>
<h1>Practice Spelling Test</h1>
<p id="aWord"> </p>
<input id="yourTurn" type="text" />
<button id="newWord">New Word</button>
<button id="checkSpell">Check My Spelling</button>
<p id="result"></p>
</body>
</html>

Related

Loop is only displaying the last string in an array when adding it a span tag

I want to change the word in the span tag every 1.5 seconds but so far it is just displaying the last word in the array 'list'.
Here is my javascript
var list = [
"websites",
"user interfaces"
];
setInterval(function() {
for(var count = 0; count < list.length; count++) {
document.getElementById("word").innerHTML = list[count];
}}, 1500);
And here is the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span id="word"></span>
</body>
</html>
You don't need a for loop, just use that setInterval, your counter or even simpler using Array manipulation:
var list = [
"websites",
"user interfaces",
"cool neh?"
];
var count = 0; // Separate your count
function changeWord() { // Separate your concerns
document.getElementById("word").innerHTML = list[count];
count = ++count % list.length; // Increment and loop counter
}
changeWord(); // First run,
setInterval(changeWord, 1500); // Subsequent loops
<span id="word"></span>
If you want to not use a counter but do it using array manipulation:
var list = [
"websites",
"user interfaces",
"cool neh?"
];
var ELWord = document.getElementById("word"); // Cache elements you use often
function changeWord() {
ELWord.innerHTML = list[0]; // Use always the first key.
list.push(list.shift()); // Push the first key to the end of list.
}
changeWord();
setInterval(changeWord, 1500);
<span id="word"></span>
P.S: The inverse would be using list.unshift(list.pop()) as you can see here.
Performance-wise the solution using counter should be faster but you have a small Array so the difference should not raise any concerns.
You may wanna try this. Not looping, just calling a changeWord function every 1.5 sec.
var list = [
"websites",
"user interfaces"
];
var count = 0;
function changeWord() {
document.getElementById("word").innerHTML = list[count];
count = count < list.length-1 ? count+1 : 0;
}
setInterval(function() { changeWord(); }, 1500);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span id="word"></span>
</body>
</html>
I would do this job by setTimeout() as follows,
function loopTextContent(a, el, dur = 1500){
var i = -1,
len = a.length,
STID = 0,
looper = _ => (el.textContent = a[i = ++i%len], STID = setTimeout(looper,dur));
looper();
return _ => STID;
}
var list = ["websites", "user interfaces", "user experience", "whatever"],
getSTID = loopTextContent(list, document.getElementById("word"));
setTimeout(_ => clearTimeout(getSTID()),10000);
<span id="word"></span>
Better use setTimeout. Every iteration should have its own timeout. See also
(() => {
const words = document.querySelector('#words');
typeWords([
"web sites",
"user interfaces",
"rare items",
"other stuff",
"lizard sites",
"ftp sites",
"makebelief sites",
"fake news sites",
"et cetera"
]);
function typeWords(list) {
list.push(list.shift()) && (words.innerHTML = list[list.length-1]);
setTimeout(() => typeWords(list), 1500);
}
})();
<div id="words"></div>
The problem with your code is whenever your interval function is called,loop get executed and prints the element because you are replacing the whole innerHtml on each iteration.
You can try the following code if u want to print whole list element again and again after interval.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<span id="word"></span>
</body>
The javascript code :
var list = [
"websites",
"user interfaces"
];
var count=0;
function print()
{
document.getElementById("word").innerHTML = list[count];
count += 1;
count%=list.length;
}
setInterval( print(), 1000);

element is getting variable without declared

I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>

Palindrome incorrect results.

I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});

Simple Javascript on html textbox conversion. Doesn't work twice

I'm using the replace method and if I type in "test test" only the first test gets converted to good so it'll become "good test". I'm at a loss on why this is happening. On a side question, if I was to add 20 other words that I would like to replace, would I have to create 20 different str.replace?
<!DOCTYPE html>
<html>
<body>
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>
<script>
function myFunction() {
var str = document.getElementById("firstbox").value.toLowerCase()
var res = str.replace("test", "good");
document.getElementById("secondbox").value = res;
}
</script>
</body>
</html>
Any help would be greatly appreciated
Use regex, change "good" to /good/g
function myFunction() {
var str = document.getElementById("firstbox").value.toLowerCase()
var res = str.replace(/test/g, "good");
document.getElementById("secondbox").value = res;
}
<p>Click the button to replace "Test" with "Good"</p>
<textarea id="firstbox"></textarea>
<textarea id="secondbox"></textarea>
<button onclick="myFunction()">Change</button>

Enter variable name in textbox and get corresponding value

I have created 3 variables a,b,c. I have assigned values to a and b and have also made a textbox. What I want to do is enter the name of a the variable in the textbox and click the button, then the textbox should should display the value assigned to that variable. It maybe very simple but I do not know what I did wrong.
Here is the FIDDLE
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=c;
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
​
Your easiest choice would be to assign your variables to a object, like this:
var vars;
function display() {
var value = document.getElementById("b1").value;
vars = {
a: 2,
b: 3,
c: value
}
if (vars.hasOwnProperty(value)) { // If the entered value is a variable name
document.getElementById("demo").innerHTML = vars[value]; // Display the variable
} else { // Otherwise
document.getElementById("demo").innerHTML = value; // display the value
}
}
Working example
The if/else can be replaced with this, to make it a little shorter:
document.getElementById("demo").innerHTML = vars.hasOwnProperty(value) // If
? vars[value] // Then
: vars.c; // Else
Try this way:
<html>
<head>
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
if(c==a){
document.getElementById("demo").innerHTML='a';
}
if(c==b){
document.getElementById("demo").innerHTML='b';
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update value.</p>
</body>
</html>
DEMO
What you are looking for is the eval() method (Which, do a quick google search, it is not recommended).
<script>
function display(){
var a = 2;
var b = 3;
var c = document.getElementById("b1").value;
document.getElementById("demo").innerHTML=(eval(c));
// if user enters b in the input field, then the html in demo will be 3
// if user enters a in the input field, then the html in demo will be 2
}
</script>
Again, not recommended!
If you declare variables directly in you script-element they are created as properties of the window-object and can be accessed as such. Thus just update your script like the following to show the contents of the variables:
<html>
<head>
<script>
var a = 2, b = 3;
function display() {
var strVarName = document.getElementById('b1').value;
if(window.hasOwnProperty(strVarName)) {
document.getElementById('demo').innerHTML = window[strVarName];
} else {
document.getElementById('demo').innerHTML = 'Variable ' + strVarName + ' does not exist.'
}
}
</script>
</head>
<body>
<input type="text" id="b1">
<button type="button" onclick="display()">Display</button>
<p id="demo">Update Value.</p>
</body>
</html>
This won't work if you declare the variables inside the display function, but this doesn't seem like a thing you would do if this code were to be used in a system to anything beside this one simple function.

Categories