this is what I have so far:
$j(element)..keypress(function(e){
var val = $j(this).val();
if ((\"1234567890.\").indexOf(e.charCode) > -1){
With the help of @elclanrs and @mgibsonbr, I came to this:
$j = jQuery.noConflict();
$j(function() {
$j("input").keypress(function(e) {
var val = $j(this).val();
var regex = /^(\+|-)?(\d*\.?\d*)$/;
if (regex.test(val + String.fromCharCode(e.charCode))) {
return true;
}
return false;
});
});
which can be tested here: http://jsfiddle.net/9U2Mw/5/
This checks a decimal number, with an optional +/- sign character. Found under 5sec in google.
/^\s*(\+|-)?((\d+(\.\d+)?)|(\.\d+))\s*$/
First, shouldn't the return be the opposite? true
if the test succeeds, false
otherwise?
Second, .
in a regex means "any character". If you want to match just a dot, use \.
This way your regex will work. However, for a better result, use the regex provided by elclanrs.
Note: it seems the value still hasn't changed when the keypress
runs, so it's the old value that is being matched, not the new one.
Update: this is not an ideal solution, but will work nonetheless - You can use the code in this question to watch for changes in the input's value (it uses polling, though):
$(element).watch("value", function(propName, oldVal, newVal) {
var regex = /^(\d*\.?\d*)$/;
if (!regex.test(newVal)){
$(this).val(oldVal);
}
});