Wrong type of variable - javascript

I have a simple javascript/jquery function that looks like this:
$("#add_a, #add_b").on("change keyup paste", function () {
var add_a = $('#add_a').val(),
add_b = $('#add_b').val(),
add = add_a + add_b;
$("#add").text(add);
});
The problem is that it treats the variables add_a and add_b as strings even though i get the value from a input with type="number". I have made other similar functions and haven't had this problem before!
To making it clear, if I type in 3 in #add_a and 4 in #add_b the result is 34 and not 7.
Is there a way to make sure it get the values as numbers or change it after?
Thanks in advance!

As you say, values from <input>s are treated as strings. You need to parse them as a number, for that, you can use parseInt:
var add_a = parseInt($('#add_a').val(), 10),
add_b = parseInt($('#add_b').val(), 10)
If you're expecting non-integer input, you can use parseFloat instead.

You can take a look here and parse the value as an Integer. If an Integer is what you want...

Related

Data changes after assigning to another variable

I work with Discord.js User object and Mongoose Schema. But the problem doesn't seems to be part of those.
var Message = require('../app/models/message'); //Mongoose Schema
...
var newMessage = new Message();
...
//taggedUser is an object containing all the info about user. id property contains user id which is number.
const taggedUser = message.mentions.users.first();
newMessage.message.to = taggedUser.id;
console.log(taggedUser.id);
console.log(newMessage.message.to);
The code above should assign user ID to Schema. Everything works, but...
442090269928849410
442090269928849400
Last 2 characters aren't the same among these variables now. How is this even possible? The = changed the actual data inside the variable?
In case it is Mongoose here is how Schema looks like:
var msgSchema = mongoose.Schema({
message : {
from : Number,
to : Number,
content : String,
time : Date
}
});
Edit:
If I change
to : Number,
to string:
to : String,
It works properly. I still need the answer on why does this work incorrectly with number. Right above the problematic line I have another id which works perfectly fine:
newMessage.message.from = msg.author.id;
I have already tried to parse taggedUser.id to integer or creating Number() object but that didn't help. So every time I turn taggedUser.id into a Number or parse it to int it changes to the slightly different number.
I don't know what to think. How can data change during the assignment?
If there is not enough data provided in the question please ask me and I'll add everything needed. I can't imagine what might be causing this bug.
9007199254740992 - Highest safe number in JS
442090269928849410 - Your integer (id)
The reason of that small variation is the 'Max precision' JavaScript can work with.
When you tried to use the id as a number it was affected by this and it changed because JavaScript can't be that precise.
If you see both numbers at the beginning of this answer you can see that they are separated by 2 characters, that is why only the 2 last character changed.
Basically your integer was affected by the max precision JS numbers can have.
Reference: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Number/MAX_SAFE_INTEGER
You might just be seeing an artifact of console.log running asynchronously. Try this:
console.log('' + taggedUser.id);
console.log('' + newMessage.message.to);
...and see if that makes any difference.

What's wrong with my delete button on my HTML/Javascript calculator

I'm trying to make a simple calculator using HTML, CSS, and Javascript. I'm done with the calculation part and the design but I'm having a hard time with my DEL button. My DEL button is supposed to backspace the last key pressed on the calculator.
I made a function called del() on my .js and this is what it looks like so far:
function del()
{
document.getElementById("dis").value = (document.getElementById("dis").value.getLength) - 1;
}
"dis" is the id of my calculator's display.
try this one
var val = document.getElementById("dis").value;
if(val.length > 0){
val = val.substring(0, val.length - 1);
document.getElementById("dis").value = val;
}
Because your code is setting the display's value to:
(document.getElementById("dis").value.getLength) - 1
Which is the number of digits (string length) of the displayed value minus one, so if the value was "500", it would set it to 2 (3-1). Clearly not what you want.
What you want is to get the value, cut it down to just the characters you want (probably with substr()) and then re-set the value to that string.
.getlength is undefined. If you want the length of the string, you should use str.length. Anyway, if you want to remove the last character, use this
str=str.substr(0,-1);
or, for your code
document.getElementById("dis").value = document.getElementById("dis").substr(0,-1);
you need to use String operations...MDN
something like this should work:
document.getElementById("dis").value = document.getElementById("dis").value.slice(0, -1)

attribute maxlength of input field is changing, but input doesn't care

I have a function to limit the number of characters that a user can type into an input field for my game. It works, except that if it goes down by 1 or more in length, the user can still enter 1 or more characters than they should be able to.
I check the inspector, and it even shows maxlength changing correctly. However, for whatever reason, it still lets the user enter in a length equal to the max number of characters that the variable was equal to during the same session. Is it a bug? Any way to get it working correctly?
my_var = 150000; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters(); //this gets called often
EDIT: http://jsfiddle.net/mDw6f/
EDITTTT:
You are using x as a global variable and is probably getting changed from something else in your code. Use var x = my_var.toString().length; (emphasis on var)
Honestly after seeing this code I was afraid there would be many more underlying problems but all I did was add var before the xyz and it works just as you want it to.
Also fixed the issue of the previous bet amount returning to the input field. It now results to a blank field.
Cheers
Real Fiddle Example
Try using this fiddle:
Working Demo
Use the html input like I did in the code, no need to specify the maxlength attribute to it.
<input type="text" class="my_input_class"/>
and the script
my_var = 25; //this var changes often, can go down to 0 or up to 1000000000
function limitNumberOfCharacters() {
x = my_var.toString().length;
$('.my_input_class').attr('maxlength', x);
}
limitNumberOfCharacters();

Javascript Sum Values

I need to sum several values in javascript. I've tried by using following code
var a = 2;
var b = 5;
c = a+b;
But, instead of calculating the values of a and b, the output (c) only combine those two values. So the output given is :
c = 25
I believe you guys can help me easily about this. Thx before. Regard Andha.
Make sure the values are numbers, otherwise they will concat instead of suming.
a = parseInt(a, 10); // a is now int
Your code is adding (concatenating) strings. Are you sure that the code you posted represents your problem? What you have written should work. Be sure in the real code you're not saying:
var a = '2'; // or something similar
Or if the values are parsed from somewhere, be sure to call parseInt(a, 10) on them before doing the addition, 10 being the radix.
Or as pointed out in the comments the Number function would probably suit your purposes.
The author has probably put "simplified" code so we can get an idea. Had same problem, while getting input values. JS interpreted it as string. Using "Number()" solved the problem:
var sum = Number(document.getElementById("b4_f2_"+i).value) + Number(document.getElementById("b4_f3_"+i).value) + Number(document.getElementById("b4_f4_"+i).value);
This works fine:
var a = 2;
var b = 5;
var c = a + b; // c is now 7
The code you show will not work the way you describe. It will result in 7.
However, when attempting to perform addition, if either or both numeric values are actually numeric strings, the other values will be cast to strings and they will be concatenated.
This is most likely to happen when attempting to read form values, reading cookies, or some other sort of HTTP header. To convert a string to a number, you need to use parseInt() [docs]. Read through the docs on it and be sure to pay attention to, and provide, the second parameter (radix) to ensure the casting from string to number uses the base you expect. (The lack of info on radix in other answers is the primary reason I went ahead and posted an answer even though others had already mentioned parseInt().)
Also, FYI, Another handy function to use when dealing with unknown values and hoping to perform mathematic operations is isNaN() [docs].
Use parseInt():
var a=2;
var b=5;
c=parseInt(a)+parseInt(b);
-Is important to apply Number() to every value. The ideal way is:
var sum = 0
sum = Number('93') + Number('7') //result 100
-instead of this way (careful with this)
var sum = 0
sum = Number('97' + '3') //result 937
-and careful with this (as variable is going to assign string type by default)
var sum = 0
sum = Number('97') + '3' //result "973"
You can simply convert string to a number by adding + before it. For somebody can be more readable.
Example:
const a = "2";
const b = "5";
const c = +a + +b
or const c = (+a) + (+b) may be more readable.
That will first convert the string to a Number.

Jquery divide cast as int issue

I am trying to divide two variables in Jquery as follows:
var image_width = parseInt($object.width());
var image_height = parseInt($object.height());
var image_ratio = image_width/image_height;
However, when I attempt to use image_ratio in an if statement...
if (image_ratio < 1) //image is taller than it is wide
{
//do something...
}
And I know that the image is taller than it is wide but the function is not entering the if statement. Is this because when two int's divide it generates an int? If so, how can I get decimal values in order to check if the ratio is less than 1?
Thanks!
what is the result of alert($object.height())? If it's possible that $object is an empty jquery collection, then.height() will return null, and parseInt(null) will return NaN, giving you NaN for image_ratio. Any comparison between NaN and another value will always return false, which would explain the behavior you're seeing.
if $object.height() is returning 0, you'll also get NaN for image_ratio, and then you need to look at your jQuery selection. Are you selecting the correct element? What does $object[0].height give you?
JavaScript doesn't have ints, only "Numbers" (double-precision floating point), so that's not the problem.
Check the actual values of each variable.
You have something else wrong because dividing two numbers will return a decimal value if they don't divide perfectly evenly. Here's a jsFiddle to see for yourself: http://jsfiddle.net/jfriend00/wnh9Q/.
var width = 4;
var height = 3;
var aspectRatio = height/width;
if (aspectRatio < 1) {
$("#if").html("Inside the if() statement."); // it goes in here
}
$("#result").html(aspectRatio); // outputs 0.75
To solve your issue, you need to look at the input values $object.width() and $object.height() and see what is wrong there.
At which point are you calling the width() and height() functions on the image object? If the image isn't yet loaded when the values are retreived, the values are probably wrong. In this case, try calculating the ratio in a function attached to the load event on the image.
No, the division doesn't give an integer result. The parseInt method doesn't give an integer result either, because there is no integer data type in Javascript.
Besides, the width and height methods returns numbers, not strings, so there is no point to parse them. That would only convert the number into a string, and then back to a number. Just get the values:
var image_width = $object.width();
var image_height = $object.height();
There is however nothing in your code that would not work, so there has to be something outside the code that you show that doesn't work.
Some possible reasons:
$object doesn't contain any elements.
The image is not loaded yet, so the element doesn't have any size.
If it's the latter, you should run your code in the load event rather than in the ready event.

Categories

Resources