I'm very new to Javascript, so I assume this is a stupid mistake.
function upvote() {
var score = parseInt(document.getElementById('voteScore').innerHTML);
score = score++;
document.getElementById('voteScore').innerHTML = score;
}
The div named "voteScore" contains the number 46 only (no HTML or anything). I am attempting to grab the string, convert it to an int, increment it and put it back in the div.
score++ increments score, you don't need to assign it back to score. Either remove the score = or change score++ to score+1.
Related
This question already has answers here:
Javascript: Converting String to Number?
(4 answers)
Closed 1 year ago.
I'm creating a cookie clicker website and whenever someone clicks the "save" button, I want their score to be saved on localstorage. so far, my code is:
let score = 0;
function addpoint() {
score += 1;
}
if (localStorage.getItem("score") !== null) {
score = localStorage.getItem("score");
}
function savegame() {
localStorage.setItem("score", score);
alert("Score has been saved successfully!")
}
}
This sort of works, but if the score variable changes, the code tries to add 1 to a string because the score was saved a string. For example, If I had five points and I saved my game, If I got another point I would have 51 points. Please help soon! I'm not sure if you need to use cookies instead. Thanks!
Local storage stores values as strings. In your case, you can convert string to number like:
if (localStorage.getItem("score") !== null) {
score = Number(localStorage.getItem("score"));
}
You could try score = parseInt(score) + 1. This way when incrementing the score, it is always parsed as an integer.
MDN - ParseInt()
What I mean is say I have a int displayed in a html page called Total. This number represent the total number of entries in the database and is stored in a table. I can access this number and display it as soon as the page is loaded.
But what I am trying to do is dynamically update this every 10 seconds to display the current count of the database.
So far I have been unsuccessful. Here is what I have been trying.
var myVar=setInterval(function () {addtext()}, 1000);
function addtext() {
var result = ${remoteFunction(controller:'run',action:'totalindb'
document.getElementById('textarea').value += "${dCounter}";
}
But what I get is either "undefined" or the same value the page loaded with.
ps This is using grails.
everything in a textarea is a string, so you can't do it "+= 1".
var String = document.getElementById('textarea');
var Number = parseInt(String.value);
Number++; or Number += 1;
I am making a game where in you click on three circles, with their ids as one, two and three, and a variable which gets a random number every onClick. If your choice on the circle and the random number matches, you get one point. I want to keep track of score. I made a variable scor, and put it to += 1, but it just appends it (011111). How can i fix this?
if(image === hidd){
document.getElementById("abc").innerHTML="ITS CORRECT!!!";
aaa.src="http://www.clker.com/cliparts/3/v/I/F/6/V/light-blue-circle-md.png";
var scor=document.getElementById("score").innerHTML
scor = scor + 1;
document.getElementById("score").innerHTML=scor;
}
else{
document.getElementById("abc").innerHTML="Try Again";
}
}
NOTE: Image variable is the choice, and hidd is the random number. abc will tell the user whether he hit the correct circle or not, and aaa is the correct option. id score is the h1 heading to display score. Please tell me wats wrong.
Thanks
Aaryamann
Convert your scor to a numeric value by placing a Unary Plus (+) operator in front of the innerHTML data you assign to it:
var scor = +document.getElementById("score").innerHTML;
^
Instead of scor + 1 to increment your value, you can use one of the following:
scor += 1; // or...
++scor; // or...
scor++;
When somebody is liking a comment on my website, a "1" is added at the right of the number where the amount of likes are shown, but when they click dislike, it does correct math.
For example:
14 + 1 = 141
14 - 1 = 13
jQuery
var elem = $('.like_button'), //Like button
num = $('.num_likes'), //Get the element: number of likes
oldnum = num.html(); //Number of likes
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(oldnum+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(oldnum-1); //Deletes one like after disliking it
}
I really wonder why disliking works but liking not.
Why does javascript interpret the value of the num element as a string, even though it is a number? Any tips for me?
Because JavaScript interprets num.html() as text. The + sign for string in javascript means concatenation, but - doesn't mean that so in that case javascript realizes you want to do numeric calculation. That's why it works with -
You should cast oldnum to an integer with parseInt().
You need to cast oldnum to a number:
if(elem.html() == "Like") {
elem.html("Dislike");
num.html(Number(oldnum)+1); //Adds one like after liking it
} else {
elem.html("Like");
num.html(Number(oldnum)-1); //Deletes one like after disliking it
}
Alternatively, +oldnum does the same thing as Number(oldnum).
Javascript is interpreting the text on your page as a string. This is because that's what text on a page normally is. Take for example:
<span id="berliner">I am a jelly donut.</span>
<script LANGUAGE="Javascript">
document.getElementById("berliner").innerHTML;
// it only makes sense that this be a string, right?
</script>
Now, in JS, you use the + sign for two things: adding numbers, or putting one string after another.
var addingnumbers = 1+1;
// adding numbers, what you want
var a = "I am";
var b = " a jelly donut";
var addingstrings = a+b;
// adding strings, which you don't want.
As such, the html was interpreted as a string like it normally should be, but in this case shouldn't be. And adding the string to the other string just appended it to the end, rather than doing math. There is an easy solution: convert the innerHTML to a number by multiplying it by 1. Multiplying can't be done to a string, so JS will change it to number form, prepping it to be added to something else.
var oldnum = num.html()*1; // done! The multiplying has changed it to a number.
And if you ever do want to change it back to a string, you can do the reverse with the toString() function.
var aNumberToStartOutWith = 3;
var aStringToEndOffWith = aNumberToStartOutWith.toString();
I made some kind a game using HTML, CSS, JS, AJAX AND PHP.
However, in order to save the user's best score, I used localStorage (for the first time).
For some reason, even though the best score is being displayed in the "best score" box while the user
is still playing (as I wanted), it's being removed when you refresh the page, and turns into 0 again (which
I defined as the default value).
Can someone please point at the problem for me?
Here is the specific part of the code:
$(".pi_tab .best_result #score").html(localStorage.record);
$("#pi_input").keyup(function() { // On pressing a digit
var num = parseInt($("#counter").html()); // Convert counter's value to integer
if (!isNaN(num)) // If it's a legal number
{
if (num + 1 > localStorage.record) // If it's the score is a new record
{
localStorage.record = num + 1; // Update record
$(".pi_tab .best_result #score").html(localStorage.record); // Show record as "Best Score"
}
}
});
Try to use this code pattern from w3schools: http://www.w3schools.com/html/html5_webstorage.asp
Use setItem and getItem to set/get the data, in my opinion your code is creating another property on localStorage object called record which more likely same as other javascript variable
Try to use the property setItem :
localStorage.setItem("key", "value");
UPDATE
Note: Name/value pairs are always stored as strings. Remember to convert them to another format when needed!
Source : W3Schools
You execute :
if (num + 1 > localStorage.getItem("record")) // If it's the score is a new record
{
localStorage.setItem("record",num + 1);
...
}
Maybe it's your problem.
Replace by :
var record = num + 1;
var localRecord = localStorage.getItem("record");
if (record > parseInt(localRecord)) // If it's the score is a new record
{
localStorage.setItem("record", record);
...
}