Richard77
Richard77

Reputation: 21611

How to prevent a page from posting back using javascript

I've checked other code, and it looks like I just need to add return false to make it work. But, it's not working because it still posts back the page.

<asp:Button ID="_btnSearch" Text="Search" 
            onclientclick="CheckForEmptySearchBox()" />

<script type = "text/javascript">
    function CheckForEmptySearchBox() 
    {
        var boxContent = document.getElementById
          ("_ctl0_contentMain__lvTSEntry_ctrl0__txtClientName").value;
        if (boxContent == null || boxContent == "") {
            alert("Please enter search criteria");

            return false;
        }
     }  
</script>

Upvotes: 2

Views: 240

Answers (2)

Aristos
Aristos

Reputation: 66641

You can add a global check on the Form and this can be done on code behind as:

    if (Page.EnableEventValidation)
    {
        if (string.IsNullOrEmpty(Page.Form.Attributes["onsubmit"]))
        {
            Page.Form.Attributes["onsubmit"] = "return CheckForEmptySearchBox();";
        }
    }

Upvotes: 1

Paul Fleming
Paul Fleming

Reputation: 24526

The source of onclientclick is receiving null rather than false because you're not returning the result of the function call.

onclientclick="return CheckForEmptySearchBox()" 

Upvotes: 5

Related Questions