I have two masks G999-9 and H99-9 which stand for graduates and honor which both need to be entered for a 开发者_Go百科single input text html control.
While first typing, if it hits a G I would like it to show the format for the Graduate format, and for the Honors, I would like it to show the format for the Honors format while typing it out. Is there a simple way to do this in javascript or jQuery?
Examples:
G111-1 H91-5 G001-3 G___-_ (If you hit G it should show the Graduate format) H__-_ (If you hit H it should show the Honors format.) ____-_ (Type anything else, or nothing do this.)
Thanks, Marc
Regex Based Demo
Yay! regex! Yes, like every other (non-HTML) parsing questions there's a regex for that. :)
$("input").keyup(function(e){
if(e.keyCode > 40 || e.keyCode < 37)
{
var validInput = $(this).val().match(/(([G])(([0-9]{3}[-]([0-9]{0,1})?|[0-9]{0,3})?)?|([H])(([0-9]{2}[-]([0-9]{0,1})?|[0-9]{0,2})?)?)/);
$(this).val(validInput?validInput[0]:"")
}
});
It's a bit convoluted (help in optimizing it would be much appreciated), but it works.
Simple way? You're either going to have to walk the string or use some fancy regex.
Normally, we'd use regexes for this, but with the assumption that you don't know so much about regexes (perhaps a bad assumption, but most people that can read them will gravitate towards them first) and in the hopes of keeping you following what is happening, I wrote it more procedurally:
<input type="text" class="formatted" />
$(document).ready(function(){
function applyMask(instr){
var pOut = [], delimitter = '-', format = 0, pSplit = 4, pMax = 6;
// There are a lot of ways to express this. I just chose one that should
// be understandable.
if ((instr.length > 0) && (instr[0].toUpperCase() == 'H'))
{
pSplit = 3;
pMax = 5;
}
pMax = Math.min(pMax, instr.length);
for (var i=0; i < pMax; i++)
{
if ((i==pSplit) && (instr[i] != delimitter))
{
pOut.push(delimitter);
}
else
{
pOut.push(instr[i]);
}
}
return pOut.join('');
}
$('.formatted').keyup(function(){
$(this).val(applyMask($(this).val()).toUpperCase());
});
});
Here's a fiddle, even: http://jsfiddle.net/UdcND/
There are some jQuery plugins for easily converting a text input to a mask edit:
a simple but useful plugin: http://www.pengoworks.com/workshop/js/mask/
another good option: http://digitalbush.com/projects/masked-input-plugin/
精彩评论