1

I'm looking to append some JavaScript to the onclick of a button on the server side. So something like

 //b is a button
 b.Attributes.Add("onclick", "my.js.here();");

but without eliminating any potentially existing onclick event on that button.

EDIT: The above represents a codebehind file (in C#) that attempts to add an additional event listener to a client side button that already might have an onclick event.

muttley91
  • 12,278
  • 33
  • 106
  • 160
  • There is only one `onclick` event, and only one bit of code that can be executed on that event. Perhaps you could join on a parent object and get the bubble up event, but that doesnt work for every object/call. – crthompson Jul 28 '14 at 19:46
  • Could it be that you are trying to register a javascript click event in codebehind? – crthompson Jul 28 '14 at 19:50
  • Yes, codebehind. Sorry for the confusion. I modified the question to clarify. – muttley91 Jul 28 '14 at 19:52
  • Well, setting a click event in the codebehind is not difficult. But you still dont get the option of keeping your existing clicks. Only one task per click. – crthompson Jul 28 '14 at 19:54
  • I believe that this answer i wrote will suit you. http://stackoverflow.com/a/22970430/2589202 – crthompson Jul 28 '14 at 19:56
  • That answers looks like exactly what I need...except that I'm using a simple `` button, not an ASP.NET button. Without modifying the existing structure, is it possible to do the same thing? – muttley91 Jul 28 '14 at 20:00
  • Just set the input button to `runat="server"` give it an ID and it should work. (feel free to upvote it ;) – crthompson Jul 28 '14 at 20:00

2 Answers2

1

I would generally try to avoid subscribing to JavaScript events using attributes. Instead, I would opt for addEventListener or some abstraction on top of that (like jQuery's .click handler). For example, continuing with the jQuery, you could use this JavaScript in your ASPX page:

$('#yourButtonId').click(function() {
      my.js.here();
 });

That has several advantages, the main of which you can add handlers without stomping on one that already exists.

You could try and do something like getting the attribute's existing value, then prepending it with my.js.here();, but that seems like a less-than-ideal solution.

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286
0

Use the below method

$("#AuthorityLevel").find("a").attr('onclick','my.js.here();');