Skip to content

Commit 46c9242

Browse files
committed
Merge pull request victorjonsson#18 from stevewasiura/patch-4
proposed change to function "lengthRestriction"
2 parents 6de21ea + dac368d commit 46c9242

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

jquery.formvalidator.js

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1044,16 +1044,25 @@ jQueryFormUtils.validateUrl = function(url) {
10441044
* @return void
10451045
*/
10461046
jQueryFormUtils.lengthRestriction = function(inputElement, maxLengthElement) {
1047-
this.input = inputElement;
1048-
this.maxLength = parseInt(maxLengthElement.text(),10);
1049-
var self = this;
1050-
1051-
$(this.input).keyup(function() {
1052-
$(this).val($(this).val().substring(0, self.maxLength));
1053-
maxLengthElement.text(self.maxLength - $(this).val().length);
1054-
})
1055-
.focus(function() {
1056-
$(this).keyup();
1057-
})
1058-
.trigger('keyup');
1047+
// read maxChars from counter display initial text value
1048+
var maxChars = parseInt(maxLengthElement.text(),10);
1049+
1050+
// bind events to this element
1051+
// setTimeout is needed, cut or paste fires before val is available
1052+
$(inputElement).bind('keydown keyup keypress focus blur', countCharacters )
1053+
.bind('cut paste', function(){ setTimeout(countCharacters, 100); } )
1054+
;
1055+
// internal function does the counting and sets display value
1056+
function countCharacters(){
1057+
var numChars = inputElement.val().length;
1058+
if(numChars > maxChars){
1059+
// get current scroll bar position
1060+
var currScrollTopPos = inputElement.scrollTop();
1061+
// trim value to max length
1062+
inputElement.val(inputElement.val().substring(0, maxChars));
1063+
inputElement.scrollTop(currScrollTopPos);
1064+
};
1065+
// set counter text
1066+
maxLengthElement.text(maxChars - numChars);
1067+
};
10591068
};

0 commit comments

Comments
 (0)