How to get number values from inputs? - javascript

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

Related

JavaScript - Using localStorage to save numbers: how to extract numbers from localStorage [duplicate]

I store a lot of values in localStorage for an app and needed a way of converting the "string" back into a number - IF it was a number. The thought being if you force HTML <input type="number"> on your form, then the data going into the form and extracted from the form IS a number, but once stored - its converted to a string. So to repopulate that field later, you must read the localStorage value and convert it back to a number before repopulating the input field - otherwise you start getting a lot of reptitive warnings and sometimes errors because NUMBERS are expected, but localStorage is retrieving strings.
My method: Assuming the value is inputted as a number, then only a number (digits only) will be stored - thus you can assume only numbers will come out (even if they are a string). Knowing only numbers will come back allows for this:
var allVariables = {} ;
var reg = new RegExp(/^\d+$/) ; // this accounts for digits only
for (var x=0; x<localStorage.length;x++) {
var keyValue = localStorage.getItem(localStorage.key(x)) ;
if (reg.text(keyValue)) {
keyValue = parseInt(keyValue) ;
}
allVariables[localStorage.key(x)] = keyValue ;
}
I even expanded on this to account for true/false booleans...can't use 0/1 easily without get confused with a number. Another method I have seen is underscoring the key name to identify the typeof for later conversion:
ie:
key1_str
key2_boo
key3_int
key4_obj
key5_flo
Then identify the "_xxx" to convert that value appropriately.
I am asking to see others approach to this problem or suggestions and recommendations on how to improve it. Mine is not perfect...though neither is localStorage...but still looking for improvement.s
suppose you have "keyName" : "12345".
Tricky solution is var newInt = +localStorage.getItem('keyName')
this extra + will convert the string to integer.
Instead of storing lots of single keys you might consider storing whole objects to less numbers of storage keys that you stringfiy to json and parse when retrieving. JSON methods will retain type
var obj= {
id:100,
anotherProp:'foo'
}
localStorage.setItem('myObj',JSON.stringify(obj));
var newObj = JSON.parse(localStorage.getItem('myObj'));
console.log(typeof newObj.id)//number
try to convert:
function getProbablyNumberFromLocalStorage(key) {
var val = localStorage.getItem(key);
return (isNan(+val) || val==null) ? val : +val;
}

Getter and setter for input HTML

I have a problem where I need to put numbers in input fields in German format. For Example, if the number is 10.5 then in German format it would be like this 10,5. It means that the . will be replaced with ,. My problem is that I need to do calculations on the numbers which means that I need to convert decimal numbers to German format and then after finishing the calculations, need to convert that value to German format again. All of this is needed to be done manually each time which is quite annoying. So, my question is that is there any way we can set a getter and a setter value for HTML inputs. I want if the value is added to the input field by any means either from jQuery change function or by entered by the user manually, it converts a decimal number i.e 10.5 the German format 10,5 and likewise, when we need to get the value of that particular input field it automatically converts the German value i.e 10,5 to a decimal number 10.5. Is there any solution for this problem? I have researched throughout the internet and couldn't get the solution.
You can make a function that returns a value getter that implements the desired functionality, a setter with the same, and the underlying element:
const makeInputWrapper = (selector) => {
const input = document.querySelector(selector);
const get = () => Number(input.value.replaceAll(',', '.'));
const set = (newVal) => {
const formatted = String(newVal).replace('.', ',');
input.value = formatted;
};
return { input, get, set };
};
const wrapper = makeInputWrapper('.foo');
const val = wrapper.get();
console.log('orig val was', val);
wrapper.set(12.56)
<input class="foo" value="4,1">

Number() when used on a string returns Nan

Here's the code I'm working on:
app.put("/transaction/:value/:id1/:id2", async(req,res) => {
try {
const {value,id1,id2} = req.params;
const bal1 = await pool.query("Select balance from balance where id=$1",[id1]);
const bal2 = await pool.query("Select balance from balance where id=$1",[id2]);
const ball1 = JSON.stringify(bal1.rows[0].balance);
const ball2 = JSON.stringify(bal2.rows[0].balance);
const convball1 = Number(ball1);
console.log(convball1);
This is a PERN project I'm trying working on and I need the convball1 value as int to further test conditions but I am not able to use it as int.
When the bal1 value was retrieved from the database, it came out as like this: [{"balance":"50"}] which is why the sanitizing at ball1. But the value at ball1 shows up as "50".
Need ball1 has an integer
Update:
I did as mentioned used parseInt() instead of Number(), but I got the same error. So, I checked the MDN web docs for the parseInt() funtion and they mention using another argument called radix.
So, a radix of 10 will convert decimal numbers to int format, but I'm not sure I'm doing it right.
Getting the same error
You mentioned you get [{"balance":"50"}] as your output;
When I do [{"balance":"50"}][0].balance I will get "50" and Number("50") will give me 50.
You are doing JSON.stringify([{"balance":"50"}][0].balance) will result in ""50"" and Number(""50"") will be Nan
Avoid JSON.stringify and you would be good.
use + sign thats it, To convert string to number
const convball1 = +ball1;
The output is coming out as JSON, so my advice is to parse it to an object using JSON.parse().
Here's an example:
const ball1 = JSON.parse('[{"balance":"50"}]');
console.log(parseInt(ball1[0].balance));
The reason your method won't work is because you try to parse an invalid number using Number(), it's invalid because it has alphabetical and specical characters like "balance" and "[]" characters included in the string, so of course it will return NaN.

wanted to add two floating number which gets concatenated as string

i want to add two float number with fixed two decimal but its converted to string and get concatenated.I know its simple question but actually i'm in hurry
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
Update when i enter input as
var a=parseFloat("7,191");
var b=parseFloat("359.55");
c=(a+b).toFixed(2)
O/P:NAN
why so?
The .toFixed() method returns a string. Call it after you've performed the addition, not before.
var a=parseFloat("15.24869");
var b=parseFloat("15.24869");
var c=(a+b).toFixed(2);
After that, c will be a string too, so you'll want to be careful.
As to your updated additional question, the output is not NaN; it's 366.55. The expression parseFloat("7,191") gives the value 7 because the , won't be recognized as part of the numeric value.
Just add parenthesys to parse float the whole result string
var a=parseFloat((15.24869).toFixed(2));
var b=parseFloat((15.24869).toFixed(2));
c=a+b
doing c = a + b adds the two answers together. You might just want to turn them into a string then concatenate them.
var a=parseFloat("15.24869").toFixed(2)
var b=parseFloat("15.24869").toFixed(2)
var c = (a.toString() + b.toString());

How can I make the script to work?

I have 3 HTML form inputs fields that is dynamically generated by a "add more" button, with naming for the fields name as fieldName, fieldName1, fieldName2, fieldName3, and so on.
Now, I'm trying to retrieve the value from this fields with JavaScript, using the script below.
var bookingForm = document.forms['formName'];
var qty = bookingForm.fieldName +'i'.value;
with the 'i' been a generated numeric number by a for loop
when I use alert(qty), it returns NaN, when I'm expecting the value for fieldName1, fieldName2, and so on.
But when I use;
var qty = bookingForm.fieldName.value
I can get the value in that field but get NaN when I try to concatenate 1,2,3, with the fieldName.
Any help will be very much appreciated.
You use brackets to access a property using a string:
var qty = bookingForm['fieldName' + i].value;
You can't use code like:
var qty = bookingForm.fieldName +'i'.value;
bookingForm.fieldName +'i' is a string. You have to change that string into a DOM element in order to access the .value parameter.
Try document.getElementsByName('fieldName'+i)[0].value

Categories