Javascript returns [object HTMLSpanElement] - javascript

I'm making a simple game for selling anchovies. I have an upgrade to buy a small fishing net. The fishing net costs a certain amount of anchovies, so I subtract that number from the total and then rewrite using innerHTML. I want this small net to add 1 anchovy every second, so I use window.setInterval. However, now every second [object HTMLSpanElement] is written to the page.
What do I do?
Here is the jsfiddle link: http://jsfiddle.net/Bj6M5/1/
And here is the code:
<head>
<script type="text/javascript">
var anchovies = 0;
var money = 0;
function goFish(num) {
anchovies = anchovies + num;
money = 0.433 * anchovies;
var money_rounded;
money_rounded = money.toFixed(2);
if (anchovies != 1) {
document.getElementById("anchovies").innerHTML = anchovies + " anchovies";
}
else {
document.getElementById("anchovies").innerHTML = "1 anchovy";
}
document.title = "$" + money_rounded + " - Anchovy Bros.";
}
function buySmallNet(){
var smallnet_price = Math.floor(10 * Math.pow(1.1,smallnets));
if (anchovies >= smallnet_price) {
smallnets = smallnets + 1;
anchovies = anchovies - smallnet_price;
if (smallnets != 1) {
document.getElementById("smallnets").innerHTML = smallnets + " small nets";
}
else {
document.getElementById("smallnets").innerHTML = "1 small net";
}
document.getElementById("anchovies").innerHTML = anchovies + " anchovies";
}
else {
alert("You don't have enough anchovies!");
}
}
window.setInterval(function(){
goFish(smallnets);
}, 1000);
</script>
<title>$0 - Anchovy Bros.</title>
</head>
<body>
<button onclick="goFish(1);">FISH!</button>
<br>
<span id="anchovies"></span>
<div style="float:right;" id="upgrades">
<center>
<button onclick="buySmallNet();">small fishing net</button>
<br>
<span>costs 15 anchovies</span>
<br>
<span id="smallnets"></span>
</center>
</div>
</body>

You're calling goFish(smallnets). smallnets is the id of an element, so you're passing that element. You're expecting a number in goFish and do all kinds of calculations and assignments, which obviously fail, because it's an element and not a number. In the end, you're outputting anchovies, which is now assigned that element, instead of the result of a calculation.
So there's a missing links somewhere where you need to convert the element to a number, which should probably be the contents of the element (being the number of small nets in posession).

The reason is this line:
goFish(smallnets);
You haven't declared a smallnets variable anywhere, but you have an element in your markup with the id "smallnets" which is a span. Most browsers create global variables for elements with id values, where the name of the variable is the id and the value is the DOM element.
Then in goFish, this line:
anchovies = anchovies + num;
is (on the first pass):
anchovies = 0 + a_span_element;
Since the span can't be reasonably converted to a number, it's converted to a string, which is "[object HTMLSpanElement]". Then the 0 is converted to a string and you have "0[object HTMLSpanElement]".
And then the next time the interval fires, you add another copy of "[object HTMLSpanElement]" to it, etc., etc.
If your goal is to use the text of the span, you want:
goFish(smallnets.innerHTML);
or better
goFish(parseInt(smallnets.innerHTML, 10));
or even better, don't rely on the global created via the id:
goFish(parseInt(document.getElementById("smallnets").innerHTML, 10));
You'll also want to put 0 or something in the span, e.g.:
<span id="smallnets">0</span>

Related

JavaScript returning null on a function for a simple guessing game

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.

How do I integrate java script into html?

I would like to know how my code could be displayed on a webpage instead of displayed in alert boxes, how do I do this. I understand that id's ect are needed but I am a little confused of where to start. Any help would be good. Thankyou!
<!DOCTYPE html>
<html>
<script>
//Set of variables
var nameCheck = /^[a-zA-Z\s]+$/;
//eliminates anything not relevant
var numberCheck = /^[0-9\.]+$/;
//eliminates anything not relevant
var totHours = 0;
//adds total gaming hours on one day
var dayHours = 0;
//how many on one such day set in i from 1-7
var averHours = 0;
//stores the average by dividing by the tothours by 7
var mostPerDay = 0;
//calculates day with most gamed
var mostOnDay = 0;
//Most hours on ONE day
var moreDays = " ";
//adds an s to the end of days if more than one
var mpd = 0;
//most per day
var ah = 0;
//average hours
var th = 0;
//total hours
var name = prompt("What is your name?");
//asks users name
//Make sure user inputs a name that includes letters and or spaces
while (name == "null" || isNaN(name) == false || !name.match(nameCheck)){
alert("Invalid Name!");
name = prompt("What is your name?");
}
//Greets the user by name
alert("Hello " + name );
//Ask how many hours gamed on a day
for (var i = 1; i <= 7; i++){
dayHours = prompt("How many hours have you gamed on day " + i + "?")
//Reask the question if the user inputs an invald answer
while (dayHours == null || isNaN(dayHours) || dayHours > 24 || !dayHours.match(numberCheck) || dayHours < 0){
alert("Incorrect! No letters or symbols, and make sure your input is under 24");
dayHours = prompt("How many hours have you gamed on day " + i + "?")
}
//Adds to total hours
totHours += Number(dayHours)
//Calculates days with most hours gamed
if (mostPerDay > dayHours){
}
else if (mostPerDay < dayHours){
mostPerDay = Number(dayHours);
mostOnDay = i;
}
else if (mostPerDay = dayHours){
mostOnDay += " and " + i;
mostPerDay = Number(dayHours);
}
}
//Adds 's' to the statistics if more than one day
if (isNaN(mostOnDay) == true){
moreDays = "s ";
}
//Divides the total hours by 7 to get average over those 7 days
aver = (totHours / 7);
//Calculates and rounds to the value of 1
th = totHours.toFixed(1);
ah = aver.toFixed(2);
mpd = mostPerDay.toFixed(1);
//States calculated statistics
alert("\nTotal gaming hours this week " + th + "\nAverage gaming hours this week " + ah + "\nMost on one day" + moreDays + mostOnDay + " for " + mpd + " hours." );
//Comments on average hours per day gamed
if (averHours <= 2){
alert("Healthy amount of gaming this week")
}
else if (averHours <= 24){
alert("Unhealthy amount of gaming this week")
}
</script>
</html>
There are several ways to include JavaScript in an HTML document:
Put the JavaScript code in a separate filename.js document and refer to it in the header of the HTML document (that is, between <head> and </head>) as follows: <script type="text/javascript" src="filename.js"></script>. This is the "cleanest" option as it separates functionality (JavaScript) from structure (HTML).
Put the JavaScript code directly in the header of the HTML document; that is, between <script type="text/javascript"> and </script> (no src attribute here)
In the body of the HTML document, again between <script> and </script>, for example when you want to dynamically add text with document.write('');
Changing the text in a <div id="mydiv"> can be done by accessing it via its id:
document.getElementById('mydiv').innerText = 'text';
or through the variants innerHTML, outerText or outerHTML.
For easy DOM manipulation, you may want to look into jQuery. Also, keep in mind that the JavaScript code in the header or external file will be executed immediately, which may cause errors if certain parts of the document body aren't loaded yet. jQuery offers an elegant solution by wrapping the code in
$(document).ready(function () {
// code here
});
Good luck!
A simple method to do this would be to include a link to an external javascript file:
<script src="path/myfile.js"></script>
at the bottom of your html file. If your script requires jQuery, make sure it is linked as an external script before your script. You can reference html elements in your javascript file by giving your html tags an id or class. For example:
In HTML:
<div id = "mydiv"> </div>
Select element in JS:
$('#mydiv')
If you are trying to make your web page more reactive, you may want to look into jquery. It's a lightweight javascript library that can help you make your web page more interactive. Check out the tutorial below:
http://www.w3schools.com/jquery/
I don't entirely understand your question, but just in case you are asking if the javascript will literally show up on your web page, it won't unless you display it as text. If you want to debug your javascript code, you can use developer tools on Chrome or something like it on other browsers:
https://developer.chrome.com/devtools

Javascript: Simple currency converter with previous conversions

what i aim to do is a very simple currency converter. Basically, you type in a number, and press a button, a text is displayed that says "x dollars is y euros". Press the button again, a new text is displayed where the old one was, and the old one is displayed under the new one.
I've come so far that when something is entered in the field, it pops up below, and if you press the button again (with the same or a different value) it becomes a list of text.
To clarify what it is i'm saying here, take a look at this jsfiddle: http://jsfiddle.net/w8KAS/5/
Now i want to make it so that only numbers work, and so that number(x) is converted when the button is pressed and displayed below next to some fitting text (like "x dollars is y euros")
This is my js code, check the jsfiddle full code (html, js, css)
Any suggestions?
var count = 0;
function validate() {
var amount = document.querySelector("#amount");
if(amount.value.length > 0) {
amount.className = 'correct';
}
else {
amount.className = 'empty';
}
if (document.querySelector('.empty')) {
alert('Något är fel');
}
else {
addconvert(amount.value);
}
}
function addconvert(amount) {
var table = document.querySelector('#tbody');
var tr = document.createElement('tr');
var amountTd = document.createElement('td');
var amountTextNode = document.createTextNode(amount);
amountTd.appendChild(amountTextNode)
tr.appendChild(amountTd);
table.insertBefore(tr, table.firstChild);
count++;
}
var button = document.querySelector(".button");
button.onclick = validate;
Your number validation is failing. Change the first part of your validation to this:
function validate() {
var amount = document.querySelector("#amount");
var amountNum = parseFloat(amount.value); //This is the numeric value, use it for calculations
if(amount.value.length > 0 && !isNaN(amountNum) ) {
amount.className = 'correct';
amount.value = amountNum;
}
...
Working here: http://jsfiddle.net/edgarinvillegas/w8KAS/6/
Cheers
You need a conversion rate (there are APIs for that), and then you can just add them together in a string
var convRate = 1.3;
var amountTextNode = document.createTextNode(amount + " dollars is " + amount*convRate + " euros");
Regarding the API, Yahoo will tell you what you need without even the need to sign-in
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDEUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
}).done(function(data) {
convRate = data.query.results.rate.Rate
});
To make sure that only numbers work, you can test the variable amount.value using the isNaN function. This will return true if the user's input is Not-a-Number, so if it returns false, you can proceed with your conversion.
if (!isNaN(amount.value)){
addconvert(+amount.value) // the plus symbol converts to a number
} else {
// display error here
}
Inside your addconvert function, you can add code to will multiply your input amount by an exchange rate to get a rough conversion.
function addconvert(){
// ...
var euros = 0.74 * amount
var text = amount + ' dollars is ' + euros + ' euros'
var amountTextNode = document.createTextNode(text);

With Javascript, how to read what is within <span> tags, when the value is created by Javascript

I have this code and I basically want it to read what is created in between the <span> tags (that value is created by another javascript script), and then take that to display 'article' or 'articles'.
<span id="quantity" class="simpleCart_quantity"></span>
<script type="text/javascript">
var q = document.getElementById('quantity');
if (q == 1) {
document.write("article");
}
else
{
document.write("articles");
}
</script>
So I want it to check <span id="quantity" class="simpleCart_quantity"></span>, and if the value that is present is '1', write 'article' and if the value is '0' or more than '1' write 'articles'. I hope you can get it.
Now it works, but only if you actually write something in between the <span>, like:
1
But the value is created externally and the script must be able to read the value that is created when the page is loaded right?
The result should be a sentence that says 'You have x article(s) in your shopping cart'.
I have no idea of how I should do this, I hope somebody can help me.
Thanks a lot!
<span id="quantity" class="simpleCart_quantity"></span>
<!-- ... --->
<span id="quantityText"></span>
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText");
if (parseInt(quantity.innerHTML, 10) === 1) {
quantityText.innerHTML = "article";
} else {
quantityText.innerHTML = "articles";
}
</script>
Note that you must use a radix argument (10, in this case) to make sure numbers are interpreted as base10. Otherwise everything starting with '0x' would be interpreted as hexadecimal (base16), for example.
alternative syntax using the ternary operator:
<script type="text/javascript">
var quantity = document.getElementById("quantity"),
quantityText = document.getElementById("quantityText"),
quantityValue = parseInt(quantity.innerHTML, 10);
quantityText.innerHTML = "article" + (quantityValue === 1 ? "" : "s");
</script>
In addition to pure javascript, you can also use jQuery:
jQuery($this).find('span.simpleCart_quantity') // find the span with class name: simpleCart_quantity
.text() // get the text

Pass variable in document.getElementByid in javascript

I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
add to cart
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
add to cart
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product

Categories