JavaScript/jQuery: Why is my increment not working? - javascript

I have two buttons and there is a form in between. One button says "+" and the other "-". I am trying to make increment/decrement buttons, but it is not properly working.
It seems like addition is causing a problem where increment is not happening, and instead, concatenation is happening. For example, when the form value is 0, and "+" button is pressed, it changes the 0 to 01.
My JavaScript code has
//assume the oldValue read 0 from the form
newValue = oldValue + 1
alert(newValue); //this returns 01 instead of 1
When the oldValue is 01 and increment again, it returns 011. Why is this not incrementing, but concatenating the 1 at the end?
Surprisingly, decrement is working perfectly with the same code except that I have a minus where there is a plus.
How can you increment a form value in peace? and can anyone explain why "+ 1" does not work?

newValue = Number(oldValue) + 1
I think you forgot to convert string to int.

Try this:
newValue = parseInt(oldValue) + 1;
This is happening because oldValue datatype is string and when you add a Int to a String then the output is also a string. So you have to convert it into a number before adding some int value into it.

CASE 1:
var a=1;
var b=2;
alert(a+b);// RESULT WILL BE 3
CASE 2:
var a='1';
var b=2;
alert(a+b);// RESULT WILL BE 12
If you are getting values from a Form or something , your value will
be treated as a string (like '1') . You can convert if to number/int
by Using the Keyword Number , Like below
alert(Number(a)+b);

Related

How to get number values from inputs?

I'm trying to recreate the "check if hit" sistem from D&D in a small aplication and I need to get numeric values vrom input fields. Problem is, the normal document.queryselector('.input-class').value, only returns streengs. Any sugestions?
yes you can cast the string with parseInt():
let text = '42px';
let my_number = parseInt(text, 10);
// returns 42
Add + before value to convert to the number.
Like:
let item = '2019';
assert(+item).toEqual(2019);
If you need some check, function isNaN() can be used after converting to number:
https://www.w3schools.com/jsref/jsref_isnan.asp

JavaScript if Statement .length not working. Why?

I have this if statement i have came up with here:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.length==2) {
Orbs+=1;
}
What this code is supposed to do is if the the "TotalMoney" value digit length equals 2,
example (the number 10 has 2 digits)
then it will add 1 "Orb" to the "Orbs" value. Currently, it does nothing. There is HTML and CSS linked to this code but i figured the problem is in this code as it works fine for everything else. Please fix it as i have been trying for hours. Thanks!
For my second question that i just found out with this code here:
var totalMoney=0;
var orbs=0;
if (totalMoney.toString().length==2) {
orbs+=1;
}
This works on getting the number value digits as 2 digits long. The problem now is that once it reaches 10, every time that number goes up (10-99) all the way up, it will add 1 orb each time. I only want it to add 1 orb only when it gets to the 2 digit number (10) and stops adding 1 orb after it reaches it. How can i achieve this? Thanks!
TotalMoney is a number, so it doesn't have a length property. You can check the length of the number by first converting to a string: TotalMoney.toString().length.
Number object in js has no length property, so TotalMoney.length return undefined.
If you want count digits you may use this:
if (TotalMoney.toString().length == 2) {
Orbs+=1;
}
But if TotalMoney will be negative, -1 for exmple, Orbs wil be incremented.
I think there are better way to find all 2-digits number:
if (TotalMoney>9 && TotalMoney<100) {
Orbs+=1;
}
TotalMoney is numeric
so to find its length use this code
TotalMoney.toString().length;
Instead of
TotalMoney.length;
so try to modify your code as below:
var TotalMoney=0;
var Orbs=0;
if (TotalMoney.toString().length==2) {
Orbs+=1;
}
Length is property of array & string.It can not be applied on other variables.
If you want to count number of digits you can do
if(TotalMoney>9)
Or you can convert it to string then check it's length
if(TotalMoney.toSting().length>2)
here are some ideas and general comments on your code.
// recommended to start with lower case. upper case such as 'TotalMoney'
// is stylistically reserved for constructors.
var totalMoney=0;
// again - changing form Orbs to orbs;
var orbs=0;
// recommended to use '===' until you are more experienced with JavaScript and
// know about the 'gotchas' that '==' might produce.
// you will be able to check the length of totalMoney only after converting it to a string.
if (totalMoney.toString().length === 2) {
orbs+=1;
}
Finally, totalMoney of 0 will not add one to orbs. But totalMoney of 10, as you mentioned, will.

jQuery: Content of html element is interpreted as a string, not an integer

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();

Jquery How to bind the last digit

i have a table like below which each content is input pop-up
on square i spot you see on last digit have 1,2,8,9 format.
in my html the content of table is value of Posisi
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
that automaticly i pick using
<td class="data206"><div align="center"><input class="data206" type="button" onclick="popup_window_show('#sample', { pos : 'tag-right-down', parent : this});setvalue(this.value);" value="A1.7.8" /></div></td>
for an example.
so my pop-up like this
my purpose to bind the last digit and then i can manipulate line value. So for an idea script will like below
$(document).ready(function(){
var posisi = $("#posisi").val();
if (posisi== like "1" or like "2" or like "8" or like "9" ){
$("#line").val("9")
}
});
My problem: I don't know how to bind the last digit in jquery..to make conditonal that $("#posisi") last digit value between 1 or 2 or 8 or 9. if this conditional true i can add value in $("#line").val("whatever i want")
need help with an example will be appreciate
Your var posisi will contain a string like "A1.7.8" and you can easily get the last character of string. This may help
How can I get last characters of a string using JavaScript
There are a few more tips which may help.
It seems that you do not want to wrap the code in document.ready. I think you want to get the last digit value on every click. so get the value in "popup_window_show" function or function you are using to show popup.
Moreover if you want to make calculation on that number i.e 1,2,8,9 then convert it into integer form first.
var posisi = $("#posisi").val();
var regex = /\.(\d+)\.?$/;
// Catches the last set of digits following a period.
// Allowing for an additional period at the end.
var matches = posisi.match(regex);
if (matches) {
var lastNumber = parseInt(matches[1], 10);
// Do something
$("#line").val(lastNumber);
}

Javascript: no idea why this solution works

Okay, I'm doing an exercise to learn Javascript, where I need to make a simple Sudoku app. There's a function to create the Sudoku field, and each little square is in a div with an id identifying the row number and column number.
Now the idea is that if a user clicks on an open field, a prompt appears asking him/her to enter a number. If the number is between 1 and 9, that number is then displayed inside the field.
I first invoked the function like this:
node.onclick=function(){fillNumber(this.id);};
This had the unexpected side-effect of making the prompt box appear three times in a row whenever a click was performed. Yet, it was clear that the first input by the user was accepted, stored and added to the div just like it was supposed to. The input from the second and third prompt box is simply lost.
I solved the problem by using the following invocation:
node.onclick=function(){if (parseInt(this.id) > 0) fillNumber(this.id);};
Yet I've no idea why this works (this is copied from a fellow student who did it this way, but doesn't know why). The value of this.id is always something like this: "11", "12", "13", "21", "22", ... So I don't even see the point of first parsing it to an int or checking whether it's bigger than 0. It always is both an int and bigger than 0 as far as I can see. Regardless, the code of the method itself didn't change and the method is invoked with the exact same argument value.
Here's the method fillNumber:
function fillNumber(id){
var input = -1;
do{
input = parseInt(prompt("Enter a number between 1 and 9: ", ""));
}while(input < 1 || input > 10);
var i = parseInt(id/10), j = id%10;
numbers[i][j] = input;
var tekst = document.createTextNode(numbers[i][j]);
document.getElementById(tekst).appendChild(tekst);
}
Can anyone explain this to me?
I may suggest you to check whether there are elements upon each other - this might be the reason for three prompts in a row.
I guess the reason the other student wrote parseInt(this.id) is the same.
He tries to parse an id into an int to escape the other clicked elements, so he makes sure the id is a valid number.
Try to use next lines:
node.onclick=function(e){
if( e.stopPropagation ) e.stopPropagation();
if( e.preventDefault ) e.preventDefault();
else e.returValue = false;
fillNumber(+this.id);
}
Note the + at +this.id parses a string to an integer or a float.

Categories