2

I am having the following element defined in my code.

    <input type="number"
       id="phone"
       required
       data-length="10"
       defaultValue={this.state.formValues.phone}
       onInput={(e) => {
          e.target.value = Math.max(0, parseInt(e.target.value)).toString().slice(0, 10)
       }}
    />

The problem here is whenever I press the key 'E, +, -', the complete value in the number field gets clear. So I just wants a solution to stop this field from taking value such as 'E, +, -' and also it should not clear the value when any of the key is pressed.

Mayank Bansal
  • 1,755
  • 2
  • 9
  • 22
  • So, the problem is `whenever I press the key 'E, +, -', the complete value in the number field gets clear` but you want `it should clear the value when any of the key is pressed` ... whaat? – Jaromanda X Apr 17 '18 at 03:55
  • @JaromandaX, I want to stop this thing i.e whenever any of the key is press, it should not accept that value neither it should clear the field value. – Mayank Bansal Apr 17 '18 at 03:56
  • Sorry, your question seemed to suggest that it's already happening – Jaromanda X Apr 17 '18 at 03:57
  • No but that is not the case. It is preventing the keys ;'E, +, -' but when I press any of the key, the complete value in the field gets cleared. @JaromandaX – Mayank Bansal Apr 17 '18 at 03:59
  • I think you should handle in `keydown` event instead of `input` event https://stackoverflow.com/a/34783480/3085279 – Tan Duong Apr 17 '18 at 03:59
  • @TanDuong,but I want that the user should not be able to type more then 10 number in this field, that is why I am using input event. – Mayank Bansal Apr 17 '18 at 04:01
  • @MayankBansal Maybe you can add 2 events :) – Tan Duong Apr 17 '18 at 04:54

1 Answers1

1

The input type number works a bit different, it will let you enter characters that are not number but when you do the value of the input will be empty, a workaround is to remove the type="number" and add an if statement to check if the parsed input value is not a number, this will happen if the user inputs a letter when the input is empty, if he inputs the letter after a number the parseInt will just get the number until the letter.

You can see the working example here

document.getElementById("phone").oninput = function(e){
    var inputValue = parseInt(e.target.value);
    if (isNaN(inputValue)){
      inputValue = 0;
    }
    e.target.value = Math.max(0, parseInt(inputValue)).toString().slice(0, 10)
};
<input id="phone"
       required
       data-length="10"
       defaultValue={this.state.formValues.phone}
    />
Liviu Boboia
  • 1,734
  • 1
  • 10
  • 21