smartType is a small and lightweight plugin that helps you bind events to a textbox when hitting Enter (e.g. saving) or hitting ESC (e.g. canceling).
The functionality it provides is very simple and its purpose is to avoid writing over and over again the same trivial code.
It’s core functionality is presented in the code snippet below. I have added a few options to enhance the plugin such as clear the textbox when hitting ESC or prevent the propagation of the keyup
event when hitting Enter.
jItem.keyup(function (e) { var isSave = e.which === 13; var isCancel = e.which === 27; if (isSave || isCancel) { var oldValue = jItem.attr(dataAttribute); var newValue = jItem.val(); if (oldValue !== newValue) { if (isSave) { if (options.requireOnSave && newValue === '') { jItem.focus(); } else { jItem.attr(dataAttribute, newValue); options.onSave(oldValue, newValue, jItem[0]); } options.preventDefaultOnSave && e.preventDefault(); } if (isCancel) { if (options.clearOnCancel) { oldValue = ''; jItem.attr(dataAttribute, oldValue); } jItem.val(oldValue); options.onCancel(oldValue, newValue, jItem[0]); } } }
Usage
jQuery('.some-textbox').smartType({ onSave: function (prev, current, textbox) { console.log('saving'); }, onCancel: function (prev, current, textbox) { console.log('canceling'); } });
It’s size is 2.1kb and if you can find it also in Github. Follow it there to get future updates. Feel free to post ideas and suggestions!
Leave a Reply