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

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

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

I'm tired too, because the ID of the control can change.

+2


source to share


5 answers


If you have a control like this:

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

      

You can do something simple, like fire a 'click' event in JS when accessing the updated client id (jQuery syntax here):



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

      

Or you can make JS work like this:

<script type="text/javascript">
  function clickFoo() {
    <%=Page.ClientScript. GetPostBackEventReference(Foo)%>;
  }
</script>

      

+9


source


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

      

If you can put javascript right in your .aspx markup, you can also get around the changing id by doing the following:



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

      

When your .aspx is processed, the button id as it appears on the page will be replaced with your javascript function.

+4


source


Easily you can use the __doPostBack function passing the ID of the control you want to fire the click event (command, etc.).

To avoid problems with the ID, do something like this:

__doPostBack("<%= yourConrol.UniqueID%>");

      

EDIT: There is an existing .Net Framework Page.GetPostBackEventReference method that emits a client-side script that triggers the postback and also provides a reference to the control that triggered the postback event.

+2


source


Using jquery puts something like this in your aspx page.

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

      

myctrl is a button. The ClientID property specifies the html button ID. JQuery offers a click function .

+2


source


You can either click a button or submit a form.

So, if you want to click a button,

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

      

or send a form

document.forms[0].submit();

      

0


source







All Articles