私は 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();
});
本当に必要なのは、テキストボックスが空の場合に入力してフォームを送信しないようにすることです。何か案は?