当表单无效时,如何停止文本框焦点?

时间:2012-03-06 13:18:52

标签: jquery asp.net asp.net-mvc-3

我在mvc3应用中写了一个简单的联系表单。一切看起来都很完美,除非所有字段都无效,因此无效提交时我的电子邮件字段上的焦点似乎存在问题。这是我正在使用的ViewModel:

public class ContactViewModel
{
    [Required(ErrorMessage="Please enter your name")]
    public string Name { get; set; }

    [Required(ErrorMessage="Please enter your email address")]
    [RegularExpression(@"^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$", ErrorMessage="Please enter a valid email address")]
    public string Email { get; set; }

    [Required(ErrorMessage="Please enter your message")]
    public string Message { get; set; }     
}

正如您所看到的,字段之间的唯一区别是我在电子邮件字段中有一个额外的正则表达式验证器。我认为这与在验证失败时跳转到这个特定字段的原因有关?

以下是我的观点代码:

@model  MSExport.Models.ContactViewModel
@{
    ViewBag.Title = "Contact";
}
@section HeaderScripts
{
    <script type="text/javascript">
        $(document).ready(function () {
            $('INPUT.auto-hint, TEXTAREA.auto-hint').focus(function () {
                if ($(this).val() == $(this).attr('title')) {
                    $(this).val('');
                    $(this).removeClass('auto-hint');
                }
                else { $(this).removeClass('auto-hint'); }
            });
            $('INPUT.auto-hint, TEXTAREA.auto-hint').blur(function () {
                if ($(this).val() == '' && $(this).attr('title') != '') {
                    $(this).val($(this).attr('title'));
                    $(this).addClass('auto-hint');
                }
            });

            IterateFields();

            $('form').submit(function () {
                AmendValues();
                if ($(this).valid()) {
                    var contactVM = {
                        Name: $('#Name').val(),
                        Email: $('#Email').val(),
                        Message: $('#Message').val()
                    };

                    $('form').slideUp('slow', function () {
                        $('#result').html("<img src='/images/loading.gif' alt='Loading' />");
                        $.ajax({
                            url: '/Contact/SubmitForm',
                            type: "POST",
                            data: JSON.stringify(contactVM),
                            contentType: "application/json; charset=utf-8",
                            success: function (result) {
                                $('#result').empty();
                                $('#result').html(result);
                            },
                            error: function () {
                                $('#result').empty();
                                $('#result').html("<p>There was a problem submitting your message. Please try again.</p>");
                            }
                        });
                    });
                }
                else {
                    IterateFields();
                    // TODO: Stop focus going to email field
                }                
            });
        });

        function AmendValues() {
            $('#contact-form-wrapper INPUT[type=text],TEXTAREA').each(function () {
                if ($(this).val() == $(this).attr('title')) { $(this).val(''); }
            });
        }

        function IterateFields() {
            $('INPUT.auto-hint, TEXTAREA.auto-hint').each(function () {
                if ($(this).attr('title') == '') { return; }
                if ($(this).val() == '') { $(this).val($(this).attr('title')); }
                else { $(this).removeClass('auto-hint'); }
            });
        }
    </script>
}

<h1>Contact</h1>
<div id="result"></div>
@using (Html.BeginForm()) { 
    <div id="contact-form-wrapper">
        <label for="Name">
            @Html.TextBoxFor(model => model.Name, new { @class = "auto-hint", @title = "Name", @tabindex = "1", @maxlength = "100" }) 
            @Html.ValidationMessageFor(model => model.Name) 
        </label>
        <label for="Email">
            @Html.TextBoxFor(model => model.Email, new { @class = "auto-hint", @title = "Email", @tabindex = "2", @maxlength = "200" }) 
            @Html.ValidationMessageFor(model => model.Email) 
        </label>
        <label for="Message">
            @Html.TextAreaFor(model => model.Message, new { @class = "auto-hint", @title = "Message", @tabindex = "3", @maxlength = "2000" })
            @Html.ValidationMessageFor(model => model.Message) 
        </label> 
        <input type="submit" value="Submit" tabindex="4" id="submit" />         
    </div> 
}

我尝试将$('#submit').focus()放在// TODO:评论的位置,将焦点转移到提交按钮。然而,这并没有解决问题,因为它似乎仍然将焦点转移到电子邮件字段,然后将其转移到提交按钮,这反过来意味着我的“自动提示”已被删除。

有什么方法可以阻止焦点被转移?如果没有,我可以以某种方式将其转移到提交按钮,而不首先转到我的电子邮件字段吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

这对你有用吗?

http://docs.jquery.com/Plugins/Validation/Reference#Focusing_of_invalid_elements

要实施选项,请按照这些文档(在选项标签下)

http://docs.jquery.com/Plugins/Validation/validate#options

e.g。

$(".selector").validate({
   focusInvalid: false
})