Adding onClick event dynamically using jQuery - javascript

Due to a plugin being used, I can't add the "onClick" attribute to the HTML form inputs like usual.
A plugin is handling the forms part in my site and it doesn't give an option to do this automatically.
Basically I have this input:
<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
I want to add an onClick to it with jQuery onload for it to be like this:
<input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
How do I go about doing this?
I know this might not be standard practice but seems like the easiest option to do in my situation.
I'm a newbie to jQuery so any help is very much appreciated.

You can use the click event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
http://api.jquery.com/click/
You can use the on event bound to "click" and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on event bound to "click" and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the
selected elements.
http://api.jquery.com/on/

try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');

Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641

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

Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});

let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");

as #Selvakumar Arumugam suggested, but the function call on registering also
$('#bfCaptchaEntry').on('click', myfunction);,
rather than use
$('#bfCaptchaEntry').on('click', () => { myfunction});

Related

How to convert jQuery to JavaScript name attribute

I'm trying to find a way to create 'on click' events for dynamically generated buttons in JS. I know that in jQuery it can be done like this:
$(document).on('click', 'name=[buttonName]', function() {});
I know the e.target method in JS, but I'm wanting to find a way to do it with a name attribute instead.
Thanks
Firstly that line of jQuery isn't quite right as the square brackets are in the wrong place:
$(document).on('click', '[name="buttonName"]', func);
To achieve the same in plain JS you would need to attach a click event handler to a static parent element, then check the name property of the clicked element:
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
// do something...
}
});
document.addEventListener('click', function(e) {
if (e.target.name == 'buttonName') {
alert('Hello!');
}
});
<button>I do nothing!</button>
<button name="buttonName">I say hello!</button>
You can use querySelector in a similar way than you would in jQuery, and attach the event listener whenever a new element is added to the DOM.
document.querySelector("button[name='buttonName']").addEventListener("click", function(){
alert("Hello, World");
});
<button name="buttonName">Click me</button>
The difference to the original jQuery code is that in that example it listens to events on the document whereas this does not.
You can use getElementByName to add click event to your button which is dynamically render
document.getElementByName("ButtonName").addEventListener("click", function(e) {
});

Trying to write a function from inline javascript

I've got some code from a developer that left our company. He wrote an inline function looking like this:
<button class="xxx" id="MyID" type="button" onclick="javascript: $('#openThis').slideToggle('slow');">btnText</button>
I've tried to remove this and put it in another function to write a callback so I can scroll to the toggled area when it's visible.
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
But I can't seem to get it to work. What am I doing wrong?
are you adding the listener before or after the object is created on the DOM?
because if you are trying to bind that onclick function without waiting the document to be ready theres no object to create the listener.
something like this could work:
$(document).on('ready', function() {
$("#MyID").click(function () {
$("#openThis").slideToggle("slow");
});
});
If you button is added dynamically then use on instead of click
Attach an event handler function for one or more events to the
selected elements.
Event handlers are bound only to the currently selected elements; they
must exist at the time your code makes the call to .on()
//Instead of document you can use a container id
$(document).on('click',"#MyID",function () {
$("#openThis").slideToggle("slow");
});
What this approach does is it adds event to a currently selected element which is document here and it will delegate the event to your selector which is #MyID in this case.
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
$(document).on('click', '#myBtn', function(){
$('#foo').slideToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<div id="foo">content</div>
<button id="myBtn">Click me</button>
You want to scroll to the area so remove the JavaScript from the button
You need to do something like this
$("#MyID").click(function() {
$('html, body').animate({
scrollTop: $("#openThis").offset().top
}, 2000);
$("#openThis").slideToggle("slow");
});
You should delete the onclick="" attributes in the button tag and in your javascript :
$("#MyID").click(function (e) {
e.preventDefault();
$("#openThis").slideToggle("slow");
});
Use the prevent default.
Hope that help

How to get the current/this object on button click using bind event?

I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});

How do button not workable

I have got this html. So, i want what CreateWorld calles once. I think this is may do with JQuery function, such as disable(). But i don't know which.
<input type="button" value="Создать мир" onclick="CreateWorld()" class="create_button"/>
I need the button to fire the first time just click on it. I can create a counter. But I think there are any simple solutions. But I do not know what
Thanks!
If you're using jQuery, and want this function to be called once:
$('.create_button').one('click',function(){
CreateWorld();
});
JS Fiddle demo.
The above will allow the event handler to fire once.
Or:
$('.create_button').click(function(){
CreateWorld;
$(this).prop('disabled',true);
});
JS Fiddle demo.
This will allow the button to have a click handler to be assigned for every click but will, after it's been clicked once, disable the button (preventing it from receiving clicks/user interaction).
To use plain JavaScript (albeit requiring a standards-compliant browser):
function buttonActions (){
CreateWorld();
this.disabled = true;
}
document.querySelector('.create_button').addEventListener('click', buttonActions);
JS Fiddle demo.
References:
('Plain') JavaScript:
addEventListener().
document.querySelector().
jQuery:
click().
prop().
one().
You can use jQuery .one() it will only listen click event once
HTML :
<input type="button" value="Создать мир" class="create_button"/>
JQUERY :
$('input.create_button').one('click',CreateWorld);
Try
$('.create_button').on('click',function(){
CreateWorld();
$(this).attr('disabled','disabled');
});
$('.create_button').on('click',function(){
if($(this).hasClass('disabled')) return;
CreateWorld();
$(this).addClass('disabled');
});
So later if you are making ajax call u can remove class to make button to work
onSuccess : $('.create_button').removeClass('disabled');
onFaulure : $('.create_button').removeClass('disabled');

Is it possible to change a .click() function in JQuery?

If I have a .click() function in the header of my page, is it possible to overwrite it later in the page?
For example if I have this in the header:
<script>
$("document").ready(function() {
$("a.lol").click(function () {
alert("aaa");
});
});
</script>
Would it be possible to change $("a.lol") to alert something else, and not alert "aaa"?
Try this,
$("document").ready(function() {
$("a.lol").click(function () { // initially the click event
alert("aaa");
});
$("a.lol").off('click');// off the click event
$("a.lol").on('click',function () { // again bind new click event with on()
alert("new click");
});
});
Read on() and off()
You can use .unbind() and then "put it back" adding a new handler.
$("a.lol").unbind('click');
Use .off()
$("a.lol").off('click');
and to add back use .on()
$("a.lol").on('click',functionName);
or
$("a.lol").on('click',function () {
//code here
});
Use $("a.lol").off('click') to remove all click handlers. Afterwards, you can install new ones.
For older versions of jQuery, use unbind()
Yes, you will have to remove the current handler with off() and then call click() again with the new handler.
// Some code
$("a.lol").off("click")
$("a.lol").click(function () {
alert("ooo");
});
PS: Depending on your use case you could maybe use one() which would trigger the handler only once and then remove itself

Categories

Resources