2

Hi does anyone have any idea to make the input field behave like this example?

https://www.westpac.com.au/personal-banking/home-loans/calculator/mortgage-calculator/

we should not allow user to delete 0 and when user type should replace 0 with the value, and when we delete all the value, the cursor will always stays at the end of the first digit.

2 Answers 2

1

The below code should work the way you want it.

function theFunction(e) {
  if (e.value <= 0) return e.value = 0
  if (e.value[0] == 0) return e.value = e.value.substring(1)
}
body{
      width: 100vw;
      height: 100vh;
}

.custom-input {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
      background-color: rgb(42, 46, 66);
      color: rgb(249, 249, 251);
      padding: 18px;
      font-size: 48px;
      height: 84px;
      margin-bottom: 18px;
      border-color: rgb(171, 175, 177);
}
<body>
      <input type="number" class="custom-input" id="custom-input" oninput="theFunction(this)" value="800">
</body>

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

3 Comments

This is exactly the behavior that i wanted. however I need it in my react component which is using textfield and react number format
you can simply wrap it inside a function, then call it within the element with the onChange attr. e.g <TextField onChange={theFunction} /> I will edit the above code to work as a function or middleware
TextField: <TextField onInput={theFunction(this)} />.... react-number-format: <NumberFormat onValueChange={theFunction(this)} />
0

I think you can use the if condition in your handleChange function, for example :

...
var result = 0;
if(input <= 0 || input == ''){
   result = 0;
} else {
   result = event.target.value;
}

this.setState({
    inputValue: result
})
...

Hope this will help you :)

1 Comment

Thanks for this.. my implementation is with react hook form and mui textfield with react-number-format. tried it and didn't work as expected.

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.