jQuery zip masking for multiple formats
Asked Answered
S

5

13

I have a requirements for masking a zip field so that it allows the classic 5 digits zip (XXXXX) or 5 + 4 format (XXXXX-XXXX).

I could so something like:

$('#myZipField').mask("?99999-9999");

but the complication comes from the fact that dash should not be showing if the user puts in only 5 digits.

This is the best I came up with so far - I could extend it to auto-insert the dash when they insert the 6th digit but the problem with this would be funny behavior on deletion (I could stop them from deleting the dash but it would patching the patch and so forth, it becomes a nightmare):

$.mask.definitions['~']='[-]';
$("#myZipField").mask("?99999~9999", {placeholder:""});

Is there any out of the box way of doing this or do I have to roll my own?

Softy answered 24/6, 2010 at 14:33 Comment(3)
I have this same issue, did you ever figure out an appropriate solution? Thanks!Dragonhead
@BenL. not really - I ended up splitting the fields in multiple text boxesSofty
This might help: igorescobar.github.io/jQuery-Mask-PluginButler
E
11

You don't have to use a different plug-in. Just move the question mark, so that instead of:

$('#myZipField').mask("?99999-9999");

you should use:

$('#myZipField').mask("99999?-9999");

After all, it isn't the entire string which is optional, just the - and onward.

Erund answered 9/11, 2012 at 20:16 Comment(0)
P
1

This zip code is actually simple, but when you have a more complex format to handle, here is how it's solved with the plugin (from the demo page):

var options =  {onKeyPress: function(cep, e, field, options){
  var masks = ['00000-000', '0-00-00-00'];
    mask = (cep.length>7) ? masks[1] : masks[0];
  $('.crazy_cep').mask(mask, options);
}};

$('.crazy_cep').mask('00000-000', options);
Prose answered 20/6, 2016 at 8:1 Comment(0)
C
0

If you're using jQuery already, there are probably hundreds of plugins for masks etc, for example: http://www.meiocodigo.com/projects/meiomask/

So I don't think you'd have to roll your own

Cribwork answered 28/6, 2010 at 13:22 Comment(0)
P
0

When you use jQuery Inputmask plugin and you want to use 4 or 5 digit values for zip code you should use:

$('#myZipField').inputmask("9999[9]");

Punctual answered 4/8, 2020 at 18:5 Comment(1)
The question asked about using ##### or #####-#### formats, not 4 or 5 digits.Imagination
C
-1

Why not have the field be transparent, and have a text object behind it with the form in light grey? So they see #######-#### in the background, and then rig it so the letters dissapear as they type. At that point, it suggests that they should enter a dash if they want to put the extra four, right? Then, you could just rig the script to autoinsert the hyphen if they mess up and type 6 numbers?

Crete answered 28/6, 2010 at 3:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.