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">
Related
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;
}
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
I want to standardise phone numbers into a +<countrycode><areacode><number> format. Problem is the input might be:
+972-54-5123456
+972545123456
972545123456
+972 (54) 5123456
00972545123456
0545123456 // especially problematic, as I have to assume it's an Israeli number
I would like to normalize all to either 972545123456 or +972545123456 format, whatever the input is. So it will probably be:
normalizeNumber('0545123456',default_country="IL")
Use Google's libphonenumber. Here's the npm:
https://www.npmjs.com/package/google-libphonenumber
Taken from that page, a usage example:
// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;
// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();
// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');
// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414
Pretty simple, just code it up:
function normalizeNumber(input, default_country) {
return String(input)
.replace(/[^+0-9]/g, '') // remove non-number (and +) characters
.replace(/^00/, '+') // replace leading 00 with +
.replace(/^0/, getCountryCode(default_country)) // replace leading 0 with default code
}
If you want you can split the statement up and add some checks, such as whether the final result starts with a + and/or is of some expected length.
The following modules could be used as a source for getCountryCode:
country-data
country-calling-codes
I'm sure this is basic stuff but I'd like any text input that's left blank to have a value of zero so it can still be included in a function and not mess with the final sum of the equation.
At the moment I'm just setting <input type="text" id="id" value="0"> since nothing will be divided by a var value = document.getElementById("id"); but I don't want to see the zeros in the text boxes.
Is there an better way to not include empty inputs in an equation?
You can use the || operator along with a default value to exclude empty text boxes (or none existent ones) all in one line:
var value = document.getElementById("id").value || "0";
Or, if you want an integer value (since it looks like you're going to do calculations):
var value = +document.getElementById("id").value || 0;
Dont set the value on the input. Don't use a placeholder either it will show in the input.
var value = document.getElementById("id").value;
if (value !== "") {
//use it here
}
Since you're searching for a numeric value to be used in a equation, you can just do all the calculations internally to avoid displaying those values in the inputs, for example:
var value = parseInt(document.getElementById("id"));
if(isNaN(value)){
value = 0;
}
You just first parse the result to int (or float, any type that works for you), then you verify if it's a valid number, and if not, then you just assign it a value of zero. That way you can use it in your equation and you will not need to display that zero in the input.
I have this bit of code, it's supposed to take the value from one field, and calculate the value from it based on a certain percentage (in this case 60%).
I created a hidden field to store the value in the html, but when I run the calculation and check it in Firebug it gets a NaN value. Can anyone tell me what I can do to produce the number I need?
(Apply_RequestedAmtX_r != 0 & Apply_RequestedAdvanceAmtY_r !=0){
var AmtX= ($('#Apply_RequestedAdvanceAmtX_r').val());
var AmtY= ($("#Apply_AmtYAfterSplit_r").val());
var MaxAMT = parseInt((AmtY*60)/100);
$('#mna').val(MaxAMT
val returns a string. Now, the way you're using those variables, they'll get automagically converted to numbers (although it's best practice to parse them yourself).
One or the other of your values has a character in it that prevents the value from being automatically converted to a number; and then since that's NaN, any math involving it will be NaN. If you examine AmtX and AmyY in Firebug before using them, you should see whatever that character is.
Again, parsing isn't the actual problem here, but you're using parseInt in exactly the wrong place (unless you were trying to use it to truncate the fractional portion of the number, in which case there are better choices). Here are the right places:
var AmtX= parseInt($('#Apply_RequestedAdvanceAmtX_r').val(), 10);
var AmtY= parseInt($("#Apply_AmtYAfterSplit_r").val(), 10);
var MaxAMT = (AmtY*60)/100;
MaxAMT will likely have a fractional portion. If you want MaxAMT to be an integer, then:
var MaxAMT = Math.round((AmtY*60)/100);
// or
var MaxAMT = Math.floor(AmtY*60)/100);
// or
var MaxAMT = Math.ceil(AmtY*60)/100);
...depending on your needs.