Call Javascript function from codebehind when button is clicked

I want to execute the javascript function when a button is pressed, and if the result is sufficient, then the server-side code will be executed on this button.

Below I am trying to do

 protected void btnAdd_Click(object sender, EventArgs e)
    {
         if (btnAddItem.Text == "Add")
            {
                string script = string.Format(@"validate()"); 

                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true); 

                if (text1.text== null)
                {
                    Addtogrid();
                                        }

and below my javascript function

function validate() {
    var arrTextBox = document.getElementsByTagName("input");
           var retVal = 1;
    for (i = 0; i < arrTextBox.length; i++) {
        if (arrTextBox[i].type == "text" && arrTextBox[i].value == "") {
            retVal = 0;

        }
    }

    if (retVal == 0) {
        alert("Validation Failed");
        return false;
    }
    else {
        alert("Validation Success");
        return true;
    }

}

I can't figure out how to capture the result of a javascript function. I am trying this for the first time. Please help me.

+3
source share
2 answers

I think the easiest way is to set up a validation function that will be called when you click a button in your markup. Therefore, your markup should look like this.

<asp:Button runat="server" ID="btnAdd" Text="My Button" OnClientClick="return validate()" OnClick="btnAdd_Click" />

OnClientClick. javascript, .

+4

u javascript .

 <script language="JavaScript" type="text/javascript">
       function validate(msg) {
    alert(msg);
   }
</script>
   <asp:Button ID="btnValidateUSR" runat="server" Text="Validate USR" CssClass="butn"  OnClick="btnValidateUSR_Click"/>

    protected void btnValidateUSR_Click(object sender, EventArgs e)
    {
        ClientScriptManager cs = Page.ClientScript;
            cs.RegisterStartupScript(this.GetType(), "ValError", "validate('"  +Resources.ErrorDescription.BalancingErrorMsg+ "');", true);

     }
+1

All Articles