【问题标题】:Suppressing form post on enter when a textbox is empty当文本框为空时,在输入时抑制表单发布
【发布时间】:2010-02-23 16:16:23
【问题描述】:

我使用的是 MVC,并不是说这有什么不同,但我有一个用于搜索的文本框。

<% using (Html.BeginForm("Index", "Search", FormMethod.Post)) { %>
            <%= Html.AntiForgeryToken() %>
            <div id="search_box">
            <span id="search-title">Search Site</span>
                <div>
                    <%= Html.TextBox("searchText", "type here, then press enter", new { @class = "search_input" })  %>
                </div>
            </div>
        <% } %>

我曾经在此文本框上设置了onbluronfocus 事件,以便在用户点击进入或退出而不输入任何内容时进行一些文本交换。但是,我将它们移动到一个 JS 文件中,因为最终我们希望通过 JS 添加其他功能,例如自动完成等。

我的 JS 的问题是它无论如何都提交。

var searchHandler = function() {

    var searchBox = "searchText";
    var defaultText = "type here, then press enter";

    var attachEvents = function() {

        $("#" + searchBox).focus(function() {
        if (this.value == defaultText) {
                this.value = '';
            }
        }).blur(function() {
            if (this.value == '') {
                this.value = defaultText;
            }
        }).keyup(function(event) {
            var searchTerms = $("#" + searchBox).val();
            if (event.keyCode == 13 && searchTerms == '') {
                return false;
            }
            else {
                return true;
            }
        });

    };

    return {

    init: function() {
            $("#" + searchBox).val(defaultText)
            attachEvents();
        }
    }
} ();

$().ready(function() {
    searchHandler.init();
});

我真正需要的是让它在文本框为空的情况下不提交表单。有什么想法吗?

【问题讨论】:

    标签: javascript jquery asp.net-mvc webforms jquery-events


    【解决方案1】:

    如果您使用 jQuery,如果不满足验证规则,则可以简单地返回 false。

    $(document).ready( function(){
        $('form').submit(function(){
           if( $('#searchText').val() == '')
              return false;
           else
              return true; //just to be explicit, not really necessary.
        });
    });
    

    或类似的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2012-06-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-18
      • 2015-06-04
      相关资源
      最近更新 更多