Reputation: 4418
I have a search box that has a default value as "Search",i need to write some javascript that checks if the value in the search box is either "Search" or empty, then i should not sent the request and i need to display "Please enter a keyword"`
Here is the code
<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;
}
On form submit i am checking it and displaying the message "Please Enter a keyword". Although the message is displayed in the text field but the request is sent(which i don't want to happen) and also on focus of the text field i want the message(please enter a keyword)to go way too
Upvotes: 0
Views: 6019
Reputation: 9323
In addition to Jeaffrey's answer, you are not using the correct comparison operators. It should be:
if(search === "Search" || search === ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}
After that change, you need to return that value from your onSubmit -
<form action="www.google.com" style="" method="post" name="searchForm" id="searchForm" onsubmit="return grabSearch();">
Upvotes: 1
Reputation: 11981
Have you tried to return false?
if(search == "Search" || search == ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}
Upvotes: 0