简体   繁体   English

验证搜索问题的文本字段

[英]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"` 我有一个搜索框,默认值为“搜索”,我需要编写一些JavaScript来检查搜索框中的值是“搜索”还是空,然后我不应该发送请求,而我需要显示“请输入关键字”

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. 除了Jeaffrey的答案外 ,您没有使用正确的比较运算符。 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 - 更改之后,您需要从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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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