dont allow typing if decimal point is already 2 - javascript

The use case is a user is allowed to input number that has decimal point less than either 2 or 1. For e.g these are the valid ones;
10.12
10.1
10.00
10
but 10.123 is invalid
I am able to do this in two different way. One using regex pattern and other by getting the position of decimal and checking how many digits are there after decimal. This way actually its working however I am facing one strange issue. The issue is when I type 10.11 and then type 2 it wont allow and if I again type 2 it will then be 10.112 but instead of typing 2 for consecutively second times If I type 3 then it wont be 10.113 rather stay in 10.11
This is how I have done
<FormulateInput
name="height"
type="number"
step=".01"
placeholder="0.0"
v-model="height"
:value="getHeightValue"
:disabled="disableHeight"
#input="updateField('height', $event)"
min="0"
/>
updateField(field, value) {
const numberOfDecimal = (field === 'height' || field === 'depth') ? 3 : 2
// const nonDecimalValue = (value.indexOf(".") >= 0) ? value.substr(0, value.indexOf(".")) : value
// const decimalValue = (value.indexOf(".") >= 0) ? value.substr(value.indexOf("."), value.length) : ''
// if (decimalValue?.length > 3) {
// debugger
// this[field] = parseFloat(value).toFixed(2)
// }
this[field] = (value.indexOf(".") >= 0) ? (value.substr(0, value.indexOf(".")) + value.substr(value.indexOf("."), numberOfDecimal)) : value;
// this[field] = +value < 0 ? 0 : value;
},
It seems like;
when I type 1 it goes to updateField
when I type .1 it again goes to updateField and value gets updated to this[field]
when I type 2 it again goes to updateField and value gets updated to the state
when I type 2 then it sees the decimal digit as 3 so it does not get updated to the state but value on forumlate is 1.122 so if I again type 2 then it does not see any changes so updateField does not get triggered so it shows 1.122. Instead if I type 3 or any digit other than 2 then it does not show 3 digits after decimal.
I hope I made my problem clear. Sorry if its confusing.
I am using vue-formulate for my form.

Related

cut the percentage from the variables

I check the cell for a blank in the database. If it's not empty, I cut off 5 percent, if not, I skip it, but I have a problem. Maybe I'm not checking for emptiness. I have after null ? '' brackets are going and they my percent stops working and outputs me just 10-2.
let one = User[0].percent // - 10% (variable one value: 100)
let two = checkingOptions.options == null ? '' : -5 // - 5%
let three = checkingFly[2] == null ? '' : - checkingFly.percent // - 2%
let mp = + one + two + three
console.log(mp)
I want him to calculate for me correctly
10-2 = 8,
But I don't know how I can do it.
The + operator is overloaded - for numbers it does addition, for strings it does concatenation. And for mixed values it coerces them to be the same type one way or the other.
One or more of your values are probably strings. Figure out which ones are strings and convert them like this:
const allPercent = Number(User[0].percent)

Javascript - How to convert string '0' to number 0

I'm trying to do error handling on 2 input values. I'm using regex to confirm that the input is always a number. The issue I'm having is that I don't want my error handling to kick in if the user literally inputs 0. Right now I'm using:
number = parseInt(incomingValue) || ""
to set my variable. The issue is that this turns '0' into ""
Its fine if an empty value becomes an empty string because I am disabling my error checking when the lengths are equal to 0, but I need to properly turn '0' into a number 0. Anyone have any ideas?
Additionally, I'd also like to turn '000' (and so forth) into a number 0
You can turn '0' or '000' into a number by just doing:
parseInt('0'); // 0
parseInt('000'); // 0
The reason your code is not working is that javascript treats 0 as a falsly value, so when you do this:
const number = parseInt('0') || ""
the expression parseInt('0') will return 0 which is falsy. As a result, the || "" will be executed which will set number to "". You'll need to separate your parseInt and your default assignment to achieve what you want.
Use "Number()":
console.log(Number('0'));
console.log(Number('000'));
console.log(typeof(Number('0')));
console.log(typeof(Number('000')));
Or put "+" before '0' and '000':
console.log(+'0');
console.log(+'000');
console.log(typeof(+'0'));
console.log(typeof(+'000'));
Or put "* 1" before or after '0' and '000':
console.log('0' * 1);
console.log('000' * 1);
console.log(typeof('0' * 1));
console.log(typeof('000' * 1));
You can use parseInt(incomingValue) to get the int value.
For comparing you can use === for equal value and equal type means (incomingValue === 0) will be true in case of incomingValue = 0.
You can try typeof to distinguish what type of variable you are receiving
typeof true === 'boolean'
typeof null === 'object'
typeof 62 === 'number'
typeof 'Hello World' === 'string'

Javascript check if decimal of HTML form field is .0 or .5

I have a javascript function that fires on change of an HTML form field which simply adds a decimal (.0) to the inputted number and checks that the value entered is between 1 and 100. It works fine but now I need to alter my function to also check that the decimal inputted is either .0 or .5 and refuse if it does not match. This is my code:
function wingsetDecimal(input) {
input.value = parseFloat(input.value).toFixed(1);
if (input.value <1 || input.value >100) {
alert("Wing Length value is above or below limits");
// accept the value and do not reset field
// input.value ='';
}
}
I don't know how to approach this issue to check if the decimal part is .0 or .5. In other words the field should be reset input.value ='' if the value inputted is, for example 10.4 but accepted if it is 10.0 or 10.5. I have tried with string.indexOf(".")==-1; to no success.
Just my two cents, but perhaps this would do the trick:
if ((input.value % 1) * 10 === 0 || (input.value % 1) * 10 === 5) {
// logic comes 'ere
}
Or as Derek has pointed out in the comments, it works in an ever shorter form:
if(!(input.value % 0.5)) {
// todo
}}
if (!(input.value * 2 % 1)) {
//there ya go
}

Number Validation Not Working

I have an input field thats only supposed to take numbers inbetween 1 and 4. If the number is inbetween 1 and 4, it runs some code. If not, it shoots an alert that tells the user to try again with a number between 1 and 4. Here is my code
var number = document.getElementById("num").value;
if(Number(number) === 1 || Number(number) === 2 || Number(number) === 3 || Number(number) === 4 ){
//success code here///
}
else if(Number(number) !== 1 || Number(number) !== 2 || Number(number) !== 3 || Number(number) !== 4) {
} alert("Please type a whole number between(and including) 1 and 4 into the input field.");
I learned that the '.value;' function returns a string, even if the value is a number. So I put the var 'number' in the Number(); function that converts it to a number.
The problem is, when I type 1 into the input field. It shoots the alert even though it equals 1. None of the other numbers work either. I checked the console, and there are no syntax errors(also according to DreamWeaver). Help would be highly appreciated :)
I think you made a simple mistake of putting your alert outside the else if clause.
However there are a few other things you can do to make that a little more readable and efficient.
// Call Number() here so you only have to do it once
var number = Number(document.getElementById("num").value);
// You can also do something like parseInt(document.getElementById("num").value)
// Now check to see if Number() or parseInt() actually parsed an integer out of their input
// and then check that if it's outside your number range
if (isNaN(number) || number < 1 || number > 4) {
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
} else {
// Do Successful code
}
we can write like this also
var patt1 = /[1-4]/g;
if(patt1.test(number)){
//success code here///
}
else{
alert("Please type a whole number between(and including) 1 and 4 into the input field.");
}

I want spinner to display numbers properly

I have 2 questions:
Question 1: I have a spinner function and I have one slight problem with it. If a user types in 00000009 or 00021 in the spinner for example, if the user clicks away from the spinner, it will still display 00000009 or 00021 in the spinner. What I want is that if something like this happens, then what I want is that when the user clicks away, I want the spinner to display it as 9 or 21 rather than 00000009 or 00021. I don't know how to do this though. Does anyone know how to overcome this:
Question 2: If I used backspace to remove a number from a spinner and that is left with a blank spinner, what needs to be done so that if I click away from the spinner, the last number in the spinner re-appears in the spinner?
My main spinner function:
function Spinner(elem,min, max){
this.elem = elem;
this.elem.value = min;
this.min = min;
this.max = max;
this.timer;
this.speed = 150; //milliseconds between scroll values
var selfO = this;
this.elem.onkeyup = function(){
var regex = /^[0-9]*$/;
if(!regex.test(selfO.elem.value)){
selfO.elem.value = selfO.elem.value.substring(0,selfO.elem.value.length-1);
return;
}
selfO.validateValue();
}
this.validateValue = function(){
if(Number(selfO.elem.value) > selfO.max) {selfO.elem.value = selfO.max;}
if(Number(selfO.elem.value) < selfO.min) {selfO.elem.value = selfO.min;}
}
this.stopSpinning = function(){
clearTimeout(selfO.timer);
}
this.spinValue = function(dir){
selfO.elem.value = Number(selfO.elem.value) + dir;
selfO.validateValue();
selfO.timer = setTimeout(function(){selfO.spinValue(dir);},selfO.speed);
}
};
window.onload=function(){
//create the Spinner objects
var SpinnerHours = new Spinner(document.getElementById('txtHours'),0,23);
}
To return a number like 00000009 as 9 use parseInt();
alert( parseInt(000000009, 10) ); // returns 9
As pointed out by Jonathan Lonowski The second parameter is the radix.
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
//question 2 answer
var input='';
document.getElementById('inputName').onkeydown=function(e){
e = e || window.event;
keycode = e.keyCode || e.which;
if(keycode !== 8 || keycode !== 46){//backspace and delete keycodes
input=this.value;
}
}
//question 1 answer
document.getElementById('inputName').onblur=function(){
var a=this.value;
if(isNaN(a)){
this.value=input-0;
}
else{
this.value=a-0;
}
}
What this does is when a user is entering a number it saves the value unless the are pressing delete or backspace. Then when the input loses focus it checks and if there is not a valid number there it changes it to the saved value. Also the onblur get rid of any extra zeroes. Also, you will need to add more to the part that checks the input. For instance changing any non-numeric input to ''. In other words it isn't idiot proof.

Categories

Resources