jQuery maskedinput和表单重置

时间:2012-10-01 20:04:56

标签: jquery maskedinput

我正在使用Josh Bush的jQuery的Masked Input插件(Masked Input) 在ZipCode和电话号码字段上的典型地址输入表单上。

当我在表单中显示记录并在相关字段上设置输入掩码时,表单最初显示格式化的zip(99999-9999)和电话号码(999)999-9999。

当我发出表单重置时,输入掩码格式化消失了,我留下了原始字段值999999999和9999999999的zip和phone。

这些字段在获得焦点时会正确格式化,但我希望它们在重置后立即正确格式化。

任何想法如何使用通用解决方案,而无需将焦点放在表单上的所有字段?

我考虑过将“data-inputmask”属性添加到相应的字段并调用一个泛型函数,该函数使用该属性在表单加载时建立输入掩码,但这个例子是我实际维护的代码的简化并且访问项目中每次使用inputmask是不可行的。

以下是表单和脚本的简化版本:

<form action="/User/UpdateAddress" id="AddEditAddress" method="post" novalidate="novalidate">
    <input id="AddressId" name="AddressId" type="hidden" value="A5A715C7-C5DD-4793-A3D8-CE101F83224B" />
    <label for="FirstName" title="First Name">First Name</label>
    <input id="FirstName" name="FirstName" type="text" value="John" />
    <label for="LastName" title="Last Name">Last Name</label>
    <input id="LastName" name="LastName" type="text" value="Doe" />
    <label for="Address1" title="Address 1">Address 1</label>
    <input id="Address1" name="Address1" type="text" value="123 Main St" />
    <label for="Address2" title="Address 2">Address 2</label>
    <input id="Address2" name="Address2" type="text" value="Apartment 123" />
    <label for="City" title="City">City</label>
    <input id="City" name="City" type="text" value="Anytown" />
    <label for="State" title="State">State</label>
    <input id="State" name="State" type="text" value="PA" />
    <label for="ZipCode" title="Zip Code">Zip Code</label>
    <input id="ZipCode" name="ZipCode" type="text" value="191234567" />
    <label for="Phone" title="Phone">Phone</label>
    <input id="Phone" name="Phone" type="text" value="2155551234" />        
</form>
<button id="FormReset">Reset</button>
<button id="FormSubmit">Submit</button>
<script type="text/javascript">
    $("input#ZipCode").inputmask("99999-9999");
    $("input#Phone").inputmask("(999)999-9999");
    $("button#FormReset").on("click", function(){
        $("form#AddEditAddress")[0].reset();
    });
    $("button#FormSubmit").on("click", function(){
        $("form#AddEditAddress")[0].submit();
    });
</script>

1 个答案:

答案 0 :(得分:0)

为什么不在单击重置按钮时尝试重新分配输入掩码。

$("button#FormReset").on("click", function(){
        $("form#AddEditAddress")[0].reset();
        $("input#ZipCode").unmask().inputmask("99999-9999");
        $("input#Phone").unmask().inputmask("(999)999-9999");
});