简体   繁体   English

禁止在空白表格字段中搜索

[英]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. 在调试错误显示在“onclick =”返回IsEmptySearch()“”帮助。

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 . 如果搜索为空,则您的函数返回true ,但是为了阻止您的表单被提交,您必须返回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. 如果文本框具有默认提示文本,则也不会触发。

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

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