Wednesday, July 13, 2011

Masking a HTML TextField as Numeric or Float

Add these functions to your JavaScript code under <script> tag.

function getKey(evt) { // works for IE, Netscape, Firefox, Opera, Chrome

var theEvent = evt || window.event;

var key = theEvent.keyCode || theEvent.which;

return key;

}

function MaskNumeric(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;

}

}

function MaskFloat(evt) {

//8 Delete, 39 left cursor, 37 right cursor, 35 end, 36 home, 9 tab, 116 f5

//127 Backspace 48-57 0-9

var key = getKey(evt);

if( (key == 116 || key == 8 || key == 9 || key == 39 || key == 37 || key == 35 ||

key == 36 || key == 189 || key == 109 || key == 127 || key == 46 || key == 110 || key == 190) ||

(key >= 48 && key <= 57) ||

(key >= 96 && key <= 105) ) {

return true;

} else {

return false;

}

}


Then use the following code in your HTML form.

For Numeric Masked Field:

<input type="text" onkeypress="return MaskNumeric(event);" />

For Float Masked Field.

<input type="text" onkeypress="return MaskNumeric(event);" />


No comments: