JQuery Masked input plugin not working

I added JQuery Masked Input plugin for my web project, but it doesn't work at all.

The plugin can be found here: http://digitalbush.com/projects/masked-input-plugin

I have included JQuery libray and Masked Input plugin in my JSP and named the function mask

for my element html <input>

:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <!-- JS --->
    <script src="js/jquery-1.11.0.js"></script>
    <script src="js/masked-input-jquery-1.3.1.js"></script>

    <title>Test</title>
</head>
<body>

    <script type="text/javascript">
       $("#name").mask("99/99/9999");

    </script>

    <form id="" method="" action="">
    <div>
       <label for="name">
          Name<b style="color: red">*</b>
       </label>
       <input name="studentName" maxlength="255" autofocus="autofocus" type="text" id="name"/> 
......

      

When I access my JSP, even before I enter anything into the textbox, the following appears in the Chrome console:

Uncaught ReferenceError: iMask is not defined

Could you help me? Is there something wrong with the code?

+2


source to share


3 answers


This may or may not fix your current problem, but your .mask call will not work because it is executed before the rest of the page (where your input fields are) has been parsed.

You need to wrap the call in jQuery document ready mode:

$('document').ready(function() {
    $("#name").mask("99/99/9999");
});

      



This tells the script to wait until the page has loaded enough for the browser to be aware of the input fields in the document.

As an additional comment, it is best to use script tags (with some exceptions) just before the closing body tag. Otherwise, you must move the script tag to the head with the rest of the tags.

+6


source


This is because jQuery is loaded but not ready yet. Try



$(function(){
// your code goes here
});

      

+2


source


You need to wrap your jQuery in document.ready as mentioned by several people. You also need to adjust the mask to match the desired input. I assume you only want alpha characters. This JSFiddle shows your example with this assumption.

If you need an alphanumeric expression to just replace 'a' with '*'. Below is the jQuery code:

$(function() {
   //The # of "a"s you enter depends on your max field input
   //The "?" makes any character after the first one optional
   $("#fname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa"); 
   $("#lname").mask("a?aaaaaaaaaaaaaaaaaaaaaaaa"); 
});

      

It should also be said that using a masked input plug-in may not be the best option for name validation, as it is intended for fixed width inputs. If you want to test for alpha characters of different lengths, think about that instead.

+1


source







All Articles