2

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.

7
  • 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. Commented Jul 28, 2014 at 19:46
  • Could it be that you are trying to register a javascript click event in codebehind? Commented Jul 28, 2014 at 19:50
  • Yes, codebehind. Sorry for the confusion. I modified the question to clarify. Commented Jul 28, 2014 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. Commented Jul 28, 2014 at 19:54
  • I believe that this answer i wrote will suit you. stackoverflow.com/a/22970430/2589202 Commented Jul 28, 2014 at 19:56

2 Answers 2

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.

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

1 Comment

Do you mean to call this JavaScript from the server side?
0

Use the below method

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

Comments

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.