我有一个搜索框,其默认值为“搜索”,我需要编写一些javascript来检查搜索框中的值是“搜索”还是空,然后我不应该发送请求而我需要显示“请输入关键字”`
这是代码
<div id="search">
<form action="/" style="" method="post" name="searchForm" id="searchForm" onSubmit="grabSearch();">
<img src="/images/bg_search_left.jpg" id="search_box_left" width="5" height="32" alt="" />
<input id="search_box" type="text" value="Search" onblur="if (this.value == '') {this.value = 'Search';}" onfocus="if (this.value == 'Search') {this.value = '';}"/>
<input type="image" id="search_arrow" src="/images/bg_search_right.jpg" width="34" height="32" />
<input type="hidden" name="_page" value="SEARCH" />
<input type="hidden" name="_action" value="SEARCH" />
<input type="hidden" name="searchTerm" value="" />
</form>
</div>
function grabSearch(){
var search=document.getElementById('search_box').value;
if(search="Search"||search=""){
document.getElementById('search_box').value="Please Enter a keyword"
}
search=encodeSearch(search);
document.forms['searchForm'].searchTerm.value = search;
}
在表单提交上,我正在检查它并显示消息“请输入关键字”。虽然消息显示在文本字段中但请求已发送(我不想发生)以及文本字段的焦点我想要消息(请输入关键字)也是如此
答案 0 :(得分:1)
除了Jeaffrey's answer之外,您没有使用正确的比较运算符。它应该是:
if(search === "Search" || search === ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}
在更改之后,您需要从onSubmit返回该值 -
<form action="www.google.com" style="" method="post" name="searchForm" id="searchForm" onsubmit="return grabSearch();">
答案 1 :(得分:0)
您是否尝试过返回false?
if(search == "Search" || search == ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}