简体   繁体   中英

Validation of the text field for search problems

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

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

Have you tried to return false?

if(search == "Search" || search == ""){
    document.getElementById('search_box').value="Please Enter a keyword";
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM