我正在使用 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();
});
我真正需要的是让它在文本框为空的情况下不提交表单。有任何想法吗?