Skip to content

Instantly share code, notes, and snippets.

@apipkin
Created February 22, 2010 22:13
Show Gist options
  • Save apipkin/311579 to your computer and use it in GitHub Desktop.
Save apipkin/311579 to your computer and use it in GitHub Desktop.
YUI.add('echofin-form-remaining',function(Y){
var _counters = {};
var Remaining = {
ERROR_CLASS : 'echofin-form-error',
attachCharacterCounter : function (node, max_chars, message, message_node) {
if (node != null && message_node != null) {
// add to counters[] above
_counters[node.get('id')] = {
textNode : node,
messageNode : message_node,
maxChars : max_chars,
messageTemplate : message
};
node.on('keydown', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
this.handleKeyDown(e.currentTarget, code, e);
}, Y.Echofin.Form);
node.on('keyup', function(e) {
this.handleKeyUp(e.currentTarget);
}, Y.Echofin.Form);
this.handleKeyUp(node);
}
},
handleKeyDown : function (node, keyCode, e) {
// find info associated with this node
var maxlength = _counters[node.get('id')].maxChars;
var currentText = node.get('value');
var length = currentText.length;
if(length >= maxlength && !(keyCode == 46 || keyCode == 8 || (keyCode > 36 && keyCode < 41))){
e.preventDefault();
}
},
handleKeyUp : function (node) {
//find info associated with this node
var id = node.get('id');
var maxlength = _counters[id].maxChars;
var messageTemplate = _counters[id].messageTemplate;
var messageNode = _counters[id].messageNode;
var currentText = node.get('value');
var length = currentText.length;
remainingCharacters = maxlength - length;
if (remainingCharacters < 0) {
messageNode.addClass(this.ERROR_CLASS);
} else {
messageNode.removeClass(this.ERROR_CLASS);
}
messageTemplate = this.renderMessage(messageTemplate, maxlength, remainingCharacters);
this.updateMessage(messageNode, messageTemplate);
},
updateMessage : function (messageNode, message) {
messageNode.set('text', message);
},
/**
* creates the message from the template provided
* @param {Object} message the message to render
* @param {Object} maxChars %m in the message, if it exists
* @param {Object} charCount %c in the message, if it exists
*/
renderMessage : function (message, maxChars, charCount) {
m = message.replace('%m', maxChars);
return m.replace('%c', charCount);
}
};
Y.namespace('Echofin.Form').Remaining = Remaining;
}, '0.1',{requires:['node','event']});
Y.Echofin.Form.Remaining.attachCharacterCounter(Y.one('#description_list'), 360, '%m-character maximum. You have %c character(s) left.', Y.one('#description_list').ancestor().one('p.description'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment