I would like to implement a thousand space separator in a ReadOnly input type number, but when trying to do so, it doesn't seem to be working and I can only write three numbers, and then the whole thing disappears.
<input
type="number"
onChange={props.onInputChange}
value={props.value ? props.value : 0}
min={props.min}
max={props.max}
readOnly="readonly"
/>
export const priceFormatterSpace = (price) => {
return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
};
How can I do it?
This should do the trick. You have to change your input to type="text"
and first remove non-numeric characters then format the digits. You can only have a limited set of characters in input fields that are type="number"
. Chrome only allows one period or comma per value.
export default function App() {
const [value, setValue] = useState("");
// Format value by the thousands. Add a comma between
const numberWithCommas = (num) => {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// Remove non-numeric characters from input
const removeNonNumeric = (num) => {
return num.toString().replace(/[^0-9]/g, "");
}
// Handle user typing into the input
const handleChange = (e) => {
const inputValue = numberWithCommas(removeNonNumeric(e.target.value))
setValue(inputValue);
};
return (
<input type="text" onChange={handleChange} value={value} />
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.