开发者

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 empt开发者_StackOverflow中文版y.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜