Annsa, Building your Business Advantage

1 /* 2 This sample code is provided by Annsa Ltd. for information only. 3 */ 4 5 // Simple helper to return the "exMaxLen" attribute for 6 // the specified field. Using "getAttribute" won't work 7 // with Firefox. 8 function GetMaxLength(targetField) 9 { 10 return targetField.exMaxLen; 11 } 12 13 // 14 // Limit the text input in the specified field. 15 // 16 function LimitInput(targetField, sourceEvent) 17 { 18 var isPermittedKeystroke; 19 var enteredKeystroke; 20 var maximumFieldLength; 21 var currentFieldLength; 22 var inputAllowed = true; 23 var selectionLength = parseInt(GetSelectionLength(targetField)); 24 25 if ( GetMaxLength(targetField) != null ) 26 { 27 // Get the current and maximum field length 28 currentFieldLength = parseInt(targetField.value.length); 29 maximumFieldLength = parseInt(GetMaxLength(targetField)); 30 31 // Allow non-printing, arrow and delete keys 32 enteredKeystroke = window.event ? sourceEvent.keyCode : sourceEvent.which; 33 isPermittedKeystroke = ((enteredKeystroke < 32) 34 ||(enteredKeystroke >= 33 && enteredKeystroke <= 40) 35 ||(enteredKeystroke == 46)) 36 37 // Decide whether the keystroke is allowed to proceed 38 if ( !isPermittedKeystroke ) 39 { 40 if ( ( currentFieldLength - selectionLength ) >= maximumFieldLength ) 41 { 42 inputAllowed = false; 43 } 44 } 45 46 // Force a trim of the textarea contents if necessary 47 if ( currentFieldLength > maximumFieldLength ) 48 { 49 targetField.value = targetField.value.substring(0, maximumFieldLength) 50 } 51 } 52 53 sourceEvent.returnValue = inputAllowed; 54 return (inputAllowed); 55 } 56 57 // 58 // Limit the text input in the specified field. 59 // 60 function LimitPaste(targetField, sourceEvent) 61 { 62 var clipboardText; 63 var resultantLength; 64 var maximumFieldLength; 65 var currentFieldLength; 66 var pasteAllowed = true; 67 var selectionLength = GetSelectionLength(targetField); 68 69 if ( GetMaxLength(targetField) != null ) 70 { 71 // Get the current and maximum field length 72 currentFieldLength = parseInt(targetField.value.length); 73 maximumFieldLength = parseInt(GetMaxLength(targetField)); 74 75 clipboardText = window.clipboardData.getData("Text"); 76 resultantLength = currentFieldLength + clipboardText.length - selectionLength; 77 if ( resultantLength > maximumFieldLength) 78 { 79 pasteAllowed = false; 80 } 81 } 82 83 sourceEvent.returnValue = pasteAllowed; 84 return (pasteAllowed); 85 } 86 87 // 88 // Returns the number of selected characters in 89 // the specified element 90 // 91 function GetSelectionLength(targetField) 92 { 93 if ( targetField.selectionStart == undefined ) 94 { 95 return document.selection.createRange().text.length; 96 } 97 else 98 { 99 return (targetField.selectionEnd - targetField.selectionStart); 100 } 101 }
Copyright © 1997 - 2008 Annsa Limited