I'm trying to format the values typed by the user in realtime, I'm doing this for some data types but the only one that I cannot make it work is with currency (number). Based on my other data types I'm trying to solve it with the following code:
<input type="number" onkeypress="return parseFloat(this.value).toFixed(2).toLocaleString() " />
<input type="number" onkeypress="something(this.value);" />
function something(val) {
return parseFloat(val).toFixed(2).toLocaleString();
}
function something(val) {
return parseFloat(val).toFixed(2).toLocaleString();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" onkeypress="return parseFloat(this.value).toFixed(2).toLocaleString() " />
<input type="number" onkeypress="something(this.value);" />
What I'm trying to is that for example: if my user is trying to type 25999.84125 change the input value to 25999.84 but, any of my code examples are working.
How can I solve this? I'll prefer to keep the event function inside the input tag (example 1) but if the solution is writing a custom function it's okay. Also I'm open to use Regex.
CodePudding user response:
For using changing the value real-time, don't return the data in the function, just set the value to the input ! Also you cannot do it exactly real-time with JS, you need to use onChange function like this:
function something(val, input) {
document.getElementById(`input${input}`).value = parseFloat(val).toFixed(2).toLocaleString();
}
<input id="input1" type="number" onChange="something(this.value, 1);" />
<input id="input2" type="number" onChange="something(this.value, 2);" />
finally, if you want to do it exactly real time, use Vue js
CodePudding user response:
I cannot vote as I am new here but the "Raymond Shafiee" answer is correct and acceptable otherwise if you jump into Vue (which i definitely suggest you) you can simply bind values to key and watch it for changes and change it as per required