This is code I've written for a class assignment. The assignment reads as follows:
"Build a function that will start the program. Please call it main().
From the main() function, call a function called getValue().
The getValue() function will get a number from the user that will be used for the next step.
Also from the main() function, call a function called getSquareRoot().
The getSquareRoot() function will get the square root of the number that was received by the user in the getValue() function.
Make sure that you display the results, including the original number and the square root of the number, to the user in an easily readable statement.
Bolding is included in the original, by the way.
Here's my code and it works, except that somehow functions are being called twice, and results are being displayed twice, with the second iteration assigning userInput a value of 0. I can't seem to identify where the 'loop' is getting fired off (beginner here). Any help would be very much appreciated; I know I'n staring at it but it's totally eluding me.
<html lang="en">
<head>
<title>Project 3 Part A</title>
<meta charset="utf-8">
<script>
function main()
{
var msg1="";
var msg2="";
var userInput = "";
getValue(userInput);
getSquareRoot(userInput);
}
function getValue(userInput)
{
var userInput = document.getElementById("userNumber").value;
return getSquareRoot(userInput);
}
function getSquareRoot(userInput)
{
squareRoot = Math.sqrt(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
</script>
</head>
<body>
<br>
<input type="button" id="userInputButton" onclick="javascript:main();" value="Square root input value: "/>
<input type="text" id="userNumber">
</div>
<div id="original">
</div>
<div id="results">
</div>
</body>
enter code here
You need to remember that each function should optimally have 1 purpose only. The function 'getSquaredRoot' here is in charge of both calculating the root as well as outputting the result for the user to see.
Plus as Lucky Chingi said, you're calling getSquaredRoot twice.
function main()
{
var userInput = getValue();
var squaredRoot = getSquareRoot(userInput);
var msg1 = "Your original number was " + userInput + ".";
var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";
document.getElementById("original").innerHTML += msg1;
document.getElementById("results").innerHTML += msg2;
}
function getValue()
{
return document.getElementById("userNumber").value;
}
function getSquareRoot(userInput)
{
return Math.sqrt(userInput);
}
Notice how it's logically seperated now.
Related
I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.
I need help with how to code this program in javascript. The javascript code should load a character from a box and a number (N) from another box. When you press a button, N rows prints each one of those with N characters (same characters that are loaded are printed). Before printing, check that it is only available a character in the box where characters are to be entered.
code in html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p id="theText"></p>
<p id="theNumber"></p>
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<script type="text/javascript" src="script.js" ></script>
</body>
</html>
Code in Javascript:
function printOut(){
var theText = document.getElementById("theText").innerHTML;
document.getElementById("theText").innerHTML=
document.getElementById("theChar").value;
var theNumber = document.getElementById("theNbr").innerHTML;
document.getElementById("theNumber").innerHTML=
document.getElementById("theNbr").value;
var newText= theText;
var outPut;
for(i = 0; i<theNumber; i++){
newText =newText + theText;
}
newText = newText + "<br>";
for( i = 0; i< theNumber; i++){
outPut = outPut + newText;
}
document.getElementById("theText").innerHTML= outPut;
}
There are several issues in your code, even after the corrections you made after comments were made. Some of the more important:
Don't use innerHTML on an input element. It makes no sense. To get its value, use value.
Don't assign to document.getElementById("theNumber").innerHTML: it will replace any HTML you already had, and thus will remove the theNbr input. Any reference to it will fail with an error from now on.
Initialise your variables before reading from them. outPut is never initialised and so outPut + newText will give undesired results.
Although your can do this with for loops, there is a nice string method in JavaScript with which you can repeat a character or even a longer string: repeat.
Here is how it could work:
function printOut(){
var theNumber = document.getElementById("theNbr").value; // Don't use innerHTML
var theChar = document.getElementById("theChar").value;
var oneLine = theChar.repeat(theNumber) + "<br>";
var output = oneLine.repeat(theNumber);
document.getElementById("theText").innerHTML = output;
}
a charachter: <input type="charachter" id="theChar">
a number: <input type="number" id="theNbr">
<button onclick="printOut()">print out!</button>
<p id="theText"></p>
I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.
I debugged my code plenty, but I am still having issues. This is a class assignment and I asked my professor and he is stunned as well. I am certain that fixing this error will help me with my code, but what I got wrong I am not sure. Could you help? Here is the error
Here my html code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Magic Word - Sample</title>
<script src="magicWord.js"></script>
</head>
<body>
<div>
<h2 align="center">WELCOME TO MAGIC WORD!</h2>
<h3>Please enter your guess on the space below:</h3>
<div>
<input type="text" id="guestGuess" />
<input type="submit" id="submitButton" onclick="javascript:enteredGuess();" />
</div>
</div>
<div>
<h3>Your guesses so far are: </h3>
<div id="userGuesses"></div>
<div>You have guessed: <span id="userAttempts"></span> times</div>
</div>
</body>
</html>
Here is my Javascript
var numOfAttempts = 5;
var numOfGuesses = 0;
var magicWord = "Just";
function guessesUsed(attemptsTaken) {
var numGuessesLeft = document.getElementById("userAttempts");
numGuessesLeft.innerHTML = attemptsTaken;
}
//function guessesLeft(attemptsLeft) {
// var numGuessesUsed = document.getElementById("guessesLeft");
// numGuessesUsed.innerHTML = attemptsLeft;
//}
function listWordsUsed(wordUsed) {
var userTrials = document.getElementbyId("userGuesses").innerText;
var divisor = document.createElement("div");
divisor.innerHTML = "<div id=" + wordUsed + ">" + wordUsed + "</div>";
userTrials.appendChild(divisor);
return;
}
function enteredGuess()
{
//A user will enter a word and the word will be checked against the magic word
//var enterGuess = prompt("What is your guess?", "Enter your guess here");
var theGuess = document.getElementById("guestGuess");
var magicWordResult;
// Used lower case for both instances to compare both words
if (theGuess.value.toLowerCase() == magicWord.toLowerCase())
{
//The user guesses the correct word
magicWordResult = "Your guess was" + theGuess + "! Nice going!";
//document.writeln("Your guess was: " + guestGuess + "\nand the magic word is " + magicWord);
}
else //The user guesses wrong
{
//When user gets it wrong increase by one the numOfGuesses
numOfGuesses ++;
magicWordResult = "Your guess was" + theGuess + ". Nice try, but that's wrong, try again. \nYou have used " + numOfGuesses + " guesses.";
// Subtract the amount of guesses from the amount of attempts
var guessesLeft = numOfAttempts - numOfGuesses;
if (numOfGuesses == numOfAttempts)
{
// When the user has reached all its attemps
magicWordResult = "Sorry, you ran out of guesses. The magic word was " + magicWord + ".";
}
else
{
magicWordResult = "You still have " + guessesLeft + " guesses left.";
}
//To show the number of guesses the user has used
guessesUsed(numOfGuesses);
//To show the number of guesses the user has left
//guessesLeft(guessesLeft);
//Creates a list of the words used by the user
listWordsUsed(theGuess);
}
// Display in an alert mode and show how the user is doing
alert(magicWordResult);
}
Where is my error?
This:
var userTrials = document.getElementbyId("userGuesses").innerText;
gets the text of the "userGuesses" element as a string, but here:
userTrials.appendChild(divisor);
your code treats it as if it were a DOM node. Because there's no "appendChild" property on a String instance, it's undefined, and that explains the error — you're trying to make a function call but the function reference is undefined instead.
edit — oh also that typo in "getElementById()" is also important, as noted by crclayton in a comment. I missed that one :) The general trick to dealing with the
undefined is not a function
error is to try and find a place where your code might come up with undefined instead of a reference to a function. The primary causes, in my experience, are:
Typos, like the "getElementbyId" thing. If the function name is misspelled, JavaScript won't understand that and so it can't give a better error.
Unsatisfied assumptions about what a variable or property refers to, as in the userTrials variable.
Assumption that some function returns a reference to a function, when it in fact (might) return undefined
Error: Uncaught ReferenceError: myFunction is not defined
This is my .js file which isn't working or calling on my HTML
function = myFunction()
{
var ret = "";
for (var i = 15; i < 26; i++)
{
ret += i + " " + i*2 + " " + i*3 + "\n";
}
alert(ret);
}
This is my HTML code:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="Test1.js"></script>
</head>
<body>
<h1> Exercise 4 - LAB 4 </h1>
<h2> Exercise 2.1 </h2>
<button type="button" onclick= "myFunction() "> Press Me </button>
</body>
</html>
Error: Uncaught ReferenceError: myFunction is not defined
Here you go:
var myFunction = function ()
{
var ret = "";
for (var i = 15; i < 26; i++)
{
ret += i + " " + i*2 + " " + i*3 + "\n";
}
alert(ret);
};
function = varName () {} is a syntax error. You can do it like this: function varName () {} without the equals sign, or you can do it the way I did it.
After a little bit of healthy admonishment from some of our fellow posters, I should point out that there is a difference between these two ways to write a function. To quote RobG: "There is no practical difference between function foo(){} and var foo = function(){}; other than when the function is created and that the first is called a FunctionDeclaration and the second a FunctionExpression." A function declaration is loaded before any code is executed, so you can can call it anywhere (before or after the function's location in the file). However, again in terms of actual location in the file, if you call a function expression before its location in the file, an error will be thrown. (You can however get around this by declaring the variable that will later be assigned to the function expression at the beginning of the file.)
function = myFunction() { /* body */ }
is invalid syntax. Didn't you get an error in the console from this? The correct syntax is either
function myFunction() { /* body */ }
or
myFunction = function() { /* body */ }
You can also write:
somename = function myFunction() { /* body */ };
However, in this case the scope of the name myFunction is just the body, it's not global.
The declaration of the function is wrong:
Javascript:
function myFunction() {
var ret = "";
for (var i=15; i<26; i++) {
ret += i + " " + (i*2) + " " + (i*3) + "\n";
}
alert(ret);
}
HTML
<html>
<head>
<script type="text/javascript" src="Test1.js"></script>
</head>
<body>
<h1>Exercise 4 - LAB 4</h1>
<h2>Exercise 2.1</h2>
<input type="button" value="Press Me" onclick="myFunction()" />
</body>
</html>