[jQuery] Transforming input as it's typed
My workplace has a lot of people doing manual entry. I'm looking to
provide some friendly automatic formatting of data as they type it.
I have working code (thus far) but I want to ensure I'm doing things
in a sane way (there's a surprising amount you can do insanely that
still works :) ).
Here's a function below that transforms a phone number - the worker
enters the digits(only), the field reflects (and could also accept)
the fully formatted version (e.g. (123) 456-7890 ).
I'm building this towards a plugin model (ala masked input with happy
coexistence with validate)
$("#example").keyup(function(){
var val = $(this).val();
if(/^[-\d\(\) ]*$/.test(val)){
var base = val.replace(/[-\(\) ]/g, '');
var size = base.length;
if(size < 3){ // Area code
// Leave unchanged
}
else if (size < 6){
val = "(" + base.slice(0,3) + ") " + base.slice(3);
}
else if(size < 11){
val = "(" + base.slice(0,3) + ") " + base.slice(3,6) + "-" + base.slice(6);
}
$(this).val(val);
}
});
Comments appreciated.
--
Brett Ritter / SwiftOne
swiftone@swiftone.org