views:

120

answers:

1

I am using MVC, not that this makes a difference, but I have a text box for searching.

<% 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>
        <% } %>

I used to have the onblur and onfocus events set on this text box to do some text swapping when the user clicked into it or out of it without typing anything. But, I moved them into a JS file because eventually, we want to add other functionality through JS, such as autocomplete, etc.

The problem with my JS is that it submits no matter what.

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();
});

What I really need is to just make it so that enter does not submit the form if the textbox is empty. Any ideas?

+2  A: 

If you use jQuery you can simply return a false if the validation rules are not met.

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

Or something close to that.

palehorse