1

I want to use jQuery Masked Input Plugin (http://digitalbush.com/projects/masked-input-plugin/) in my registration form. My form looks like that

...

<input  class="part1" type="text" name="lname"  value="Last Name" onfocus="if(this.value=='Last name') {this.style.color='#aea592';this.style.fontStyle='normal'; this.value=''};" onblur="if(this.value=='')  {this.style.color='#aea592'; this.style.fontStyle='italic'; this.value='Last name'}"  />
<input class="part2" type="text" id="dob" name="dob"  value="Date of Birth" onfocus="if(this.value=='Date of Birth') {this.style.color='#aea592';this.style.fontStyle='normal'; this.value=''};" onblur="if(this.value=='')  {this.style.color='#aea592'; this.style.fontStyle='italic'; this.value='Date of Birth'}" />

...

a the end of the file

<script src="core/code/js/mask.js"></script>
<script type="text/javascript">
jQuery(function($) {
    $('#dob').mask('99.99.9999', {placeholder:' '});
});
</script>

When you open the page, Last Name field shows word "Last name" but date of birth doesn't show anything. http://prntscr.com/2miaa How can i activate mask plugin for only onfocus event?

4

1 回答 1

6

Yarr... 好吧,首先不要在你的标记中放这么多脚本。它很难阅读,而且会更难维护。让我们先尝试分离表单的样式和功能。

编辑:可以在http://jsfiddle.net/ninjascript/RuFHK/2/找到一个工作示例

CSS

input { color: #aea592; }
input.default { font-style: italic; }

HTML

<input class="part1 default" type="text" name="lname" value="Last Name"/>
<input class="part2 default" type="text" id="dob" name="dob" value="Date of Birth"/>

JavaScript

$('input').bind('focus', function() {
    var el = $(this);
    if (el.hasClass('default')) {
        el.removeClass('default').val('');
    }
});

...好吧,这更容易理解。现在,您希望在焦点上再发生一件事,那就是对 #dob 元素中包含的值应用掩码。这是编辑的块:

$('input').bind('focus', function() {
    var el = $(this);
    if (el.hasClass('default')) {
        el.removeClass('default').val('');
    }
    if (el.attr('id') === 'dob') {
        $(this).mask('99.99.9999', {placeholder:' '});
    }
});

现在您的输入只有在获得焦点后才应该屏蔽。

如果您想确保在提交时返回一些值,您可以随时验证“模糊”上的内容。我真的不想为这个表单中的每个字段编写if语句,所以我只是要映射每个字段名称和它的默认值并引用它:

var defaultValues = {
    'lname': 'Last Name',
    'dob': 'Date of Birth'
};

现在,只要我需要用我的默认值重新填充该字段,我就可以参考该地图。在 DOB 字段的情况下,看起来输入掩码插件也有一个“取消掩码”选项。不幸的是,由于掩码中的字符是#dob 字段值的一部分,我们不能只检查空值。相反,我将使用一个正则表达式来检查一个只包含空格和 '.' 的值。字符:

$('input').bind('blur', function() {
    var el = $(this);
    var name = el.attr('name');

    // Really we only want to do anything if the field is *empty*
    if (el.val().match(/^[\s\.]*$/)) {

        // To get our default style back, we'll re-add the classname
        el.addClass('default');

        // Unmask the 'dob' field
        if (name === 'dob') {
            el.unmask();
        }

        // And finally repopulate the field with its default value
        el.val(defaultValues[name]);
    }
});
于 2011-08-13T06:27:12.567 回答