简体   繁体   中英

disallow Search on Empty form field

I have a form field and I have to see that search button is clicked only when there is some data in the form field. The following is the code.

    <script type="text/javascript">
        function IsEmptySearch(TxtField){
        var re = /\s/g; //any white space
        var str = TxtField.replace(re, "");
        if (str.length == 0) {
        return true;
        } else {return false;}
        } 
    </script>

<div>
<form id="formsearch" name="formsearch"  />
<input type="text" name="TxtField" maxlength="255" class="findSearch" value="Enter Search..." 
  onfocus="if (this.className=='findSearch') { this.className = ''; this.value = ''; }"
  onblur="if (this.value == '') { this.className = 'findSearch'; this.value = 'Enter Search...'; }"/>
<input type="button" value="Search" onclick="return IsEmptySearch()" >
</form>
</div>

The above is not working, as the form gets submitted, even though the Search field is empty.

On Debug the error is showing at "onclick="return IsEmptySearch()" " kindly help.

Try

onclick="return !IsEmptySearch()"

Your function returns true if the search is empty, but to stop your form from being submitted, you have to return a false . You can rewrite and rename your function too. Try this, enter something in the search box and see if you can submit.

Change function to following:

<script type="text/javascript">
function IsEmptySearch(txtField, defaultText){
    var re = /\s/g; //any white space
    defaultText = defaultText || "";
    var txt = txtField.value.replace(re,"");
    var ret = txt != ""  && txt != defaultText.replace(re,"");
    return ret;
}
</script>

change button to following:

<input type="submit" value="Search" 
                  onclick="return IsEmptySearch(aTextField,'Enter Search...')" >

this will also not fire if textbox has default prompt text.

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