views:

251

answers:

4

Hi,

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.

+3  A: 
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.

womp
I tried that, but for some reason it is not doing a postback. Very strange!
mrblah
I even did a $(..).attr("href") and it does output the doPost... that is in the href tag of the button.
mrblah
+2  A: 

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>
orip
+1 I think the second one is the best soluton
Cleiton
+1  A: 

That is easy you can use __doPostBack function passing the controll ID that you want the click(command etc) event get fired.

To avoid problems with ID, do something like it:

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

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

Cleiton
+1  A: 

Using jquery put something like this into your aspx page.

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

myctrl is the button. The property ClientID gives the id of the html button. Jquery offers the click function.

Christian13467
don't forget the '#' for an id selector
orip