Adding onClick event dynamically using jQuery

Due to the use of the plugin, I cannot add the "onClick" attribute to the inputs of the HTML form, as usual. The plugin processes part of the forms on my site, and it does not allow you to do this automatically.

I basically have this input:

<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style=""> 

I want to add onClick to it using jQuery onload so that it looks like this:

 <input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style=""> 

How should I do it?

I know that this may not be standard practice, but it seems that this is the easiest option in my situation.

I am new to jQuery, so any help is greatly appreciated.

+69
javascript jquery html
Sep 05 '12 at 14:50
source share
5 answers

You can use the click event and call your function or move the logic to a handler:

 $("#bfCaptchaEntry").click(function(){ myFunction(); }); 

You can use the click event and assign the function as a handler:

 $("#bfCaptchaEntry").click(myFunction); 



.click ()

Bind an event handler to a JavaScript click event, or call this event on an element.

http://api.jquery.com/click/




You can use the on event associated with the "click" and call your function or move your logic to a handler:

 $("#bfCaptchaEntry").on("click", function(){ myFunction(); }); 

You can use the on event attached to the "click" and set your function as a handler:

 $("#bfCaptchaEntry").on("click", myFunction); 



.on ()

Attach an event handler function for one or more events to selected items.

http://api.jquery.com/on/

+135
Sep 05
source share

Try a rough approach,

 $('#bfCaptchaEntry').on('click', myfunction); 

or in case jQuery is not an absolute must try below

 document.getElementById('bfCaptchaEntry').onclick = myfunction; 

However, the above method has several drawbacks, as it sets onclick as a property, rather than registering as a handler ...

Learn more about this post https://stackoverflow.com/a/212832/

+15
Sep 05
source share

try this approach if you know your client name of the object (it doesn’t matter if it is a Button or TextBox)

 $('#ButtonName').removeAttr('onclick'); $('#ButtonName').attr('onClick', 'FunctionName(this);'); 

try this if you want to add onClick event to server object using jQuery

 $('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick'); $('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);'); 
+9
Feb 11 '16 at 17:36
source share
 $("#bfCaptchaEntry").click(function(){ myFunction(); }); 
+7
Sep 05
source share

Or you can use the arrow function to define it:

 $(document).ready(() => { $('#bfCaptchaEntry').click(()=>{ }); }); 

For better browser support:

 $(document).ready(function() { $('#bfCaptchaEntry').click(()=>{ }); }); 
0
Sep 14 '17 at 22:56 on
source share



All Articles