What's the best method to mask an input field to only allow float/double, without any jquery plugin.
Acutally i'm doing it like this:
$("#defaultvalue").bind("keypress", function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
but thats only for numbers
thx
JavaScripts parseFloat() function returns NaN, when your input is not a number. For i18n you will probably have to replace the floating point separator (e.g. , with .)
parseFloat(value) and value.match('^[0-9]*\.[0-9]*$')
I guess you could drop the parseFloat and just use the regex.
In HTML page just call JS SetFloatEntry Method.
Example:
<html>
<script>
$(document).ready(function () {
SetFloatEntry("weight");
});
</script>
<body>
<input id="weight" type="text" />
</body>
</html>
Put this on your JS refered file:
/* Main function */
function SetFloatEntry(fieldName) {
$("#" + fieldName).keydown(function (event) {
return NumericField($("#" + fieldName).val(), event, true);
});
}
/* Auxiliar */
var strUserAgent = navigator.userAgent.toLowerCase();
var isIE = strUserAgent.indexOf('msie') > -1;
var reKeyboardChars = /[\x03\x08\x09\x0D\x16\x18\x1A\x2E\x23\x24\x25\x26\x27\x28\x2D]/;
var reNumber = /^((\d{1,3}\.)*\d{3}|\d*,{0,1}\d+|(\d{1,3}\.)*\d{3},{0,1}\d+|\d*)$/;
function NumericField(str, objEvent, isFloat) {
oldValue = str;
strKey = GetChar(objEvent);
if (((objEvent.which) ? objEvent.which : event.keyCode) == 13
|| (((objEvent.which) ? objEvent.which : event.keyCode) == 190 && isFloat))
return true;
if (!KeyNumber(objEvent)
&& !reKeyboardChars.test(strKey)
&& !(objEvent.ctrlKey
&& reClipboard.test(strKey)))
return false;
return true;
}
function KeyNumber(objEvent) {
return reNumber.test(GetChar(objEvent));
}
function GetChar(objEvent) {
var arrKeys = new Array();
arrKeys[96] = '0';
arrKeys[97] = '1';
arrKeys[98] = '2';
arrKeys[99] = '3';
arrKeys[100] = '4';
arrKeys[101] = '5';
arrKeys[102] = '6';
arrKeys[103] = '7';
arrKeys[104] = '8';
arrKeys[105] = '9';
arrKeys[111] = '/';
arrKeys[193] = '/';
iKeyCode = GetKeyCode(objEvent);
if (arrKeys[iKeyCode] != null)
return arrKeys[iKeyCode];
return String.fromCharCode(iKeyCode);
}
function GetKeyCode(objEvent) {
if (isIE)
return objEvent.keyCode;
return objEvent.which;
}