0

How to call function in code-behind in c# with javascript?

I have this code behind :

protected void btn_Click(object sender, EventArgs e)
{
    if (btn != null && btn.Checked)
    {
        Response.Redirect(string.Format("get.aspx?a={0}&b={1}", 
                                         a.SelectedValue, b.SelectedValue));
    }
}

And I have a Checkbox :

<asp:CheckBox ID="btn" runat="server" Checked="false" />

I am tryong to call that function btn_Click in javascript :

var btn = document.getElementById("btn");

if (btn.checked) {
    '<% = btn_Click() %>'
}

But not worked!!! Why? Thanks.

2
  • this might help you stackoverflow.com/questions/3713/… Commented Mar 25, 2014 at 13:41
  • try this document.getElementById('<%=btn.ClientID %>') and see if that works.Also alert(btn) and see if its not returning null. Also you need to do postback to call server side btn_click event. Commented Mar 25, 2014 at 13:43

2 Answers 2

1

You can do a proper ajax approach explained here -> http://www.techillumination.in/2013/07/an-aspnet-way-to-call-server-side.html

Sign up to request clarification or add additional context in comments.

Comments

0

you can do it like this using Jquery, This is not tested

var button = $("#btn");
$(button).trigger("click");

3 Comments

Not worked: var btn = $("#btn"); if (btn.checked) { $(btnV).trigger("btn_Click()"); }
did u added jquery library it is jquery and is supposed to work
in my aspx page: <script type="text/javascript" src="/jquery/js/jquery-1.7.2.min.js"></script> and the btn_Click not called ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.