3

我正在使用 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>
        <% } %>

我曾经在此文本框上设置onblur和事件,以便在用户单击或退出时进行一些文本交换而不输入任何内容。onfocus但是,我将它们移动到一个 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();
});

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

4

1 回答 1

3

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

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

或者类似的东西。

于 2010-02-23T16:20:33.550 回答