Banny Banny - 3 months ago 16
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.

HTML

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


jQuery

$("#quanText").keyup(function(){
$(this).val().replace(/[^\d\.]/g, '');
});


http://jsfiddle.net/PNaJt/

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

Answer

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

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

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

Comments