Saturday, October 2, 2010

Javascript input type=text mask and formatter example

Javascript prototype standard, work fine.

<html>
<body>
<table>
<tr>
<td><input type="text" value="0000-00-00" maxlength="10" onKeyUp="__MaskFormatter(event, '####-##-##');"
onMouseUp="__doSetCaretPosition(this, __doGetCaretPosition(this));" ></td><td></td>
</tr>
</table>

<script type="text/javascript">
function __MaskFormatter(evt, format){
try {var obj; if(evt.srcElement) obj = evt.srcElement; else obj = evt.target;
if (evt.keyCode == '8' || evt.witch == '8' || evt.keyCode == '46' || evt.witch == '46') {if(document.execCommand) document.execCommand('undo', false, null);return false;}
var locs = format;var cpos = __doGetCaretPosition (obj) - 1; if(cpos < 0) cpos = 0;
var chr = __doGetCaretChar(obj, cpos);/*String.fromCharCode(evt.keyCode);*/

if (evt.keyCode == '36' || evt.witch == '36') {__doSetCaretPosition (obj, 0); return true; }
if (evt.keyCode == '37' || evt.witch == '37' || evt.keyCode == '38' || evt.witch == '38') {__doSetCaretPosition (obj, cpos); return true;}
if (evt.keyCode == '39' || evt.witch == '39' || evt.keyCode == '35' || evt.witch == '35') {if (evt.srcElement) { if (cpos >= locs.length - 1) cpos = obj.value.length - 1;     else cpos++;__doSetCaretPosition (obj, cpos); return true;    } else { __doSetCaretPosition (obj, cpos); return true; }}

var loc = locs.charAt(cpos);__doSetCaretPosition (obj, cpos);
if (chr.length > 0) {
    if(loc == '#') { if ("0123456789".indexOf(chr.charAt(0)) == -1) __doSetCaretChar (obj, cpos, "0"); }
    else if(loc != '*') __doSetCaretChar (obj, cpos, loc);  
    __doSetCaretPosition (obj, cpos + 1);
}
return true;} catch(e) { alert(e); return false; }}

function __doGetCaretChar (oField, iCaretPos) {return oField.value.substr(iCaretPos);}
function __doSetCaretChar (oField, iCaretPos, oText) {if(oField.value.length <= 0 || oField.value.length < iCaretPos) return;oField.value = oField.value.substr(0, iCaretPos) + oText + oField.value.substr(iCaretPos+1);}
function __doGetCaretPosition (oField) {var iCaretPos = 0;if (document.selection) {oField.focus ();var oSel = document.selection.createRange();oSel.moveStart ('character', -oField.value.length);iCaretPos = oSel.text.length;} else if (oField.selectionStart) iCaretPos = oField.selectionStart;return iCaretPos;}
function __doSetCaretPosition (oField, iCaretPos) {if (document.selection) {__RemoveSelection ();    var oSel = document.selection.createRange();oSel.moveStart ('character', iCaretPos);oSel.moveEnd ('character', 1);oSel.select ();} else {oField.selectionStart = iCaretPos; oField.selectionEnd = iCaretPos + 1;oField.focus ();}}
function __RemoveSelection () {if (window.getSelection) {var selection = window.getSelection ();selection.removeAllRanges ();} else if (document.selection.createRange) {var range = document.selection.createRange ();document.selection.empty ();}}
</script>
</body>
</html>

No comments: