We help IT Professionals succeed at work.

javascript masked input textbox

maqskywalker asked
I saw this fiddle:   FIDDLE

On this fiddle, when you select a country from the drop down, it applies a different masking to the postal_code input text box.

So when you select USA it applies this to the textbox: $(".postal_code").mask("99999");
when you select Canada it applies this to the text box:  $(".postal_code").mask("a9a-9a9");

I'm transferring this fiddle to a regular html page.

This is my code so far:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
    <title>jQuery Masked Input Sample</title>
    <script src="http://code.jquery.com/jquery-1.4.3.js" type="text/javascript"></script>
    <script src="http://jquery-joshbush.googlecode.com/files/jquery.maskedinput-1.2.2.js" type="text/javascript"></script>

    <script type="text/javascript">

        jQuery(function ($) {

        $('#country').change(function () {
            //alert($('#country option:selected').val());
            if ($('#country option:selected').val() == 'US') {
                //alert(' yea ');
            } else {


    <div id="demo">
        Phone: <input class="phone"/><br/>
        Zip: <input class="zip"/>
        <select id="country" name="country" class="country">
            <option selected="selected" value="0"></option>
            <option value="CA">Canada</option>
            <option value="US">United States</option>
        <input type="text" class="postal_code" name="postal_code" />


Open in new window

When I run the page, the masking on the phone and zip textboxes works fine but the masking on the postal_code textbox is not working.

Anyone know what I'm doing wrong?  How can I fix the masking on the postal_code textbox ?
It should work just like the fiddle mentioned above.
Watch Question

Most Valuable Expert 2013
Awarded 2012
you simply have to wrap your change function into a document.ready event.

Your Javascript code is running BEFORE the HTML Dom elements are created, therefore there is no event registered :-)

		$(document).ready(function() {
          $('#country').change(function () {
            if ($('#country option:selected').val() == 'US') {
                //alert(' yea ');
            } else {

Open in new window

Just replace the above part.