MUI TextField format input to show numbers and decimals - reactjs

I'm trying to format the value of the input of this MUI component to show a maximum of 3 numbers following with a maximum of 2 decimals separated by a dot, e.g. 233.99, I want to store this value in a react state called value (const [value, setValue] = useState(0)).
I'm having trouble since I see a lot of approachs to achieve this, but I find it complicated to also keep track if the user already entered the first 3 numbers and not let him enter more while also keeping tack of the decimal values too, since as I said, there should be a maximum of 2 decimals.
I tried regex functions, toFixed js function, and more, but I can't make this work smoothly.

If I understood this correctly, you can achieve this with:
let inp = document.getElementById("input");
inp.addEventListener("keypress", ev => {
ev.preventDefault();
if (!/\d|\./.test(ev.key)) return;
inp.value = /^\d{0,3}(\.\d{0,2})?$/.test(inp.value + ev.key) ? inp.value + ev.key : inp.value;
// update state when value has changed
// if (inp.value != value) setValue(inp.value);
})
<input type="text" id="input">
Alternatively, you can use <input type="text" pattern="^\d{0,3}(\.\d{0,2})?$"> and input.checkValidity() to notify the user on submit.

Related

How to show default values for text with onChange input?

I have an object that I'm passing to a state variable:
const values = [
value1:'value1',
value2:'value2',
value3:'value3',
value4:'value4'
]
const [inputValues,setInputValues] = useState(values)
I am able to modify these values as well as display them e.g:
<Text>{inputValues.value1}</Text>
<Input value={inputValues.value1} onChange={onChange} name={value1}/>
The problem is when I'm resetting the values in the input to empty strings it will reset in the text as well, leaving it blank while the input values are changed. I currently have other state variables that will display the values separately for the text, but I don't see the point since I now have two values that does the same thing:
const [value1, setValue1] = useState()
How can I modify the input values without affecting the text fields?
You can't modify the inputValues without affecting the text fields, because both values are using the same variable, you are using the same state.
...
This would be an option if your Text were to show the default value only
const values = [
value1:'value1',
value2:'value2',
value3:'value3',
value4:'value4'
]
const [inputValues,setInputValues] = useState(values)
...
//this should be taken from your values, to be static. or from another state
<Text>{values.value1}</Text>
<Input value={inputValues.value1} onChange={onChange} name={value1}/>

How to update number from an input

I am implementing a basic web app in React and I am trying to update an integer from a number type input.
The process is fairly easy but I cannot figure out how to update regarding this process,
let's say we have this hook,
const [fee, setFee] = useState(2); // default value of fee should be 2
handlerFunc() {
// ...
}
<input type="number" onChange={handerFunc} /> which should update the fee
and this <p>Fee is{fee}$</p> should increment one by one after every 500 number is entered in that number type input.
1 for the additional 500 number in the input => 3 fee.
note: The fee should stay 2 until the input number reaches 1999 and for every additional 500 types in the input, the fee should also increment by 1.
How can I implement this handler function regarding this?
Please help.
I've not tried directly if this works as expected but the logic should be this way:
Keep the fee state in synch with the input.
<input type="number" onChange={e => setFee(parseInt(e.target.value,10))} value={fee} />
then store a value in a userRef.
const calculatedFee = useRef(0);
Use useEffect to implement your logic when the fee state change:
useEffect(() => {
if(fee === 500){ // or whatever condition you need
calculatedFee.current = 500 // or a calculated amount.
}
}, [fee]);
display the calculatedFees using the ref value;
<p>{calculatedFee.current}</p>
here is a full example: https://codesandbox.io/s/laughing-star-u4o9x?file=/src/App.js

Svelte - Binding a checkbox to toggle an input value

Using svelte, I want to set the default value of an input based on whether a checkbox is checked or not. The input is used in a drug dosage calculation. The calculation takes an value of weight in kg (k) x the input value.
I also need to have the drug calculation results change when this input value is changed by the checkbox action or when a user changes the input value manually, which doesn't happen currently.
I have been able to implement the input value change when the checkbox is checked but not clear on how to get the calculation to recalculate when the checkbox is checked or the input value is changed manually.
I need some help in integrating the correct input value into my calculation.
Checkbox:
let yes = false;
<input type=checkbox bind:checked={yes} >
Input:
<input value={yes? item.Fdosevalue : item.dosevalue} step={item.dosestep}
min={yes ? item.Fdosemin : item.dosemin} max={yes ? item.Fdosemax : item.dosemax} >
Calculation:
Not sure how to integrate the checkbox change in this calculation.
<span bind:this={k}> {( (k * item.dosevalue)).toFixed(1)} {item.appendvol} </span>
Here is a REPL which will hopefully make it a bit clearer
You can use data binding to accomplish this:
<input bind:value={...} />
You'll just need a place to store the values:
let values = {}
And then you bind to values with a unique key.
<input bind:value={values[item.name]}/>
Make sure to initialize the values dictionary with a default values for each fluid anytime the checkbox changes:
<input type=checkbox bind:value={yes} on:change={handleChange}/>
// initialize default values
function handleChange() {
const entries = fluids.map(item => {
const defaultValue = yes ? item.dosevalue : item.Fdosevalue
return [item.name, defaultValue]
})
values = Object.fromEntries(entries)
}

How to validate my input field based on formula

I am trying to validate my input field in a redux form based on a formula.
There are 4 terms in my formula. I would like to restrict the user to type/enter only these 4 terms and make a formula.
TERM1, TERM2, TERM3, TERM4
User can write something in the formula including these 4 terms
TERM1*5,
TERM2/0.2 etc
You can do something like the following.
handleValidate = (text) => {
const re = /(TERM\[1-4])/
return re.test(text)
}
The above function will return true if the text sent to it matches the pattern you specified

How to put comma separator in input field in reactjs?

i have a form where i show previous field value in input tag. But, as i put type=number. then my .toLocaleString("en-IN") would'nt work.Also, i want to show comma in INR currency styles. i.e 12,25,789
Following is my code:
<Col lg="2">
<Form.Control
size="sm"
// type="number"
value={temp.originalAmount.toLocaleString("en-IN")}
onChange={this.handlechangevalue.bind(
this,
item,
keys,
index
)}
/>
</Col>
P.S been using react-bootstrap
It's not clear for me where you want to use the comma separated values but you can change between styles with the help of regexp and replace. Something like this:
// 1234567 => 12,34,567
const encode = string => string.match(/(\d{2})(\d{2})(\d{3})/).slice(1).join(',');
// 12,34,567 => 1234567
const decode = string => string.replace(/,/g, '');
(If your input is looks like two digits / comma / two digits / comma / three digits but this can be changed easly ofc.)
Then you can convert the result to number before save into the state and the back to the comma version to display the user.
Also, I would use a text type on the input field an a regexp based validator.
I'm using similar in case of dates.
I've come across this before. What you can do is restrict the type of input in your handlechangevalue function to numbers only. If any other character appears then discard/ignore it.
Something like this:
handlechangevalue(e) {
if( parseInt(e.target.value) !== NaN ) {
this.setState({val: e.target.value});
}
}

Resources