1

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.