-1
<input type="number" min="1"  onkeyup="this.value=this.value.replace(/[^\d]/,'')"name="Qty[]" placeholder="Qty" value="0">

This is my html input and using this regular expression I am able to replace all alphabets. Input gets blanked. Although I tried putting in zero like so

onkeyup="this.value=this.value.replace(/[^\d]/,'0')"

But it does not replace it with zero. Also the above provided expression replaces the whole string, whereas I want to if I input '1234a' it just removes the 'a' . So either anyone could tell me how to replace the whole alphabets with 0 or just removes the alphabets from the input.

Sample inputs: 1234a

Intended outputs: 0 or 1234

Sabri
  • 189
  • 1
  • 1
  • 13
  • add `g` modifier `onkeyup="this.value=this.value.replace(/[^\d]/g,'')"` . Could you provide a sample input along with expected output? – Avinash Raj Jan 30 '15 at 05:33
  • ^i tried that. it still replaces the whole text. Also i updated my post for sample inputs and expected outputs. – Sabri Jan 30 '15 at 05:35

1 Answers1

4

The reason why it is so is because you won't be able to get the raw value of input[type=number] using this.value unless it's a number. In any other case, it would return an empty string. See How to get the raw value an <input type="number"> field?

Instead, what you can do is use an input type of text instead i.e.

<input type="text" min="1"  onkeyup="this.value=this.value.replace(/[^\d]/g,'0')"name="Qty[]" placeholder="Qty" value="0">

Here is the fiddle: http://jsfiddle.net/jcs2zh5e/

Also, you were missing the global modifier which would have caused the regex to not replace all the alphabets and just the first one, in cases when the user pastes some value into the field. To tackle that, added g.

Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101