Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually submit a button in asp.net using javascript?

Using javascript, I want to submit a asp.net button, how can I do this?

I know the onclick looks like: javascript:WebForm_DoPostBackWithOptions(new .....);

I am also weary because the ID of the control can change.

like image 633
mrblah Avatar asked Nov 26 '25 23:11

mrblah


2 Answers

If you have a control similar to this:

<asp:Button ID="Foo" ... />

You can something simple like fire the 'click' event in JS while accessing the updated client ID (jQuery syntax here):

$('#<%=Foo.ClientID%>').click()

Or you could get the proper JS to run like this:

<script type="text/javascript">
  function clickFoo() {
    <%=Page.ClientScript. GetPostBackEventReference(Foo)%>;
  }
</script>
like image 191
orip Avatar answered Nov 28 '25 12:11

orip


var button = document.getElementById('btnID'); 
if (button)
{ 
   button.click();
}

If you can put the javascript right in your .aspx markup, then you can get around the changing ID's as well by doing this:

var button = document.getElementById('<%= myServerButton.ClientID %>'); 
if (button)
{ 
   button.click();
}

When your .aspx is processed, the ID of the button as it appears on the page will be substituted into your javascript function.

like image 32
womp Avatar answered Nov 28 '25 13:11

womp