Banny Banny - 1 year ago 104
HTML Question

jQuery regex to remove non-numeric characters isn't working

I've been trying to validate a quantity field by using regex to determine on keyup whether or not the value contains any non-numeric characters, yet for some reason (even though i've copied straight up someone elses to test) it does not work. Here is my code.


<input type="text" id="quanText" maxlength="2" value="0"></input>


$(this).val().replace(/[^\d\.]/g, '');

I also know it isn't working because i tried
.replace(/.*/, '');
which should just make the field blank whenever i type.

Answer Source

Strings in JavaScript are immutable - you'll need to do

var value= $(this).val().replace(/[^\d\.]/g, '');

the replace() function is going to return you the replaced string which you then have to set back on 'this'

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download