I am having 2 buttons A & B and I need to call the function defined in onclick HTML attribute of button B but on click of button A.
Also I need to pass an extra
To make it simple you can set some global variables/object you want to pass into function as parameters and then call the function and use global variables/object property value.
What you say ;)
/* with variables in global scope should be accessible inside function going to call */
param1 = 1;
param2 = 2;
/* function definition */
function functionCalling(){
/* use values here */
console.log(param1, param2);
}
...
functionCalling();
...
/* with variables in global scope should be accessible inside function going to call */
param = {property1:1, property2:2};
/* function definition */
function functionCalling(){
/* use values here of object */
console.log(param.property1, param.property1);
}
...
functionCalling();
...
You can do it like this, i.e. use attr
instead of prop
to get the string value of b's onclick, afterwards replace the arguments p,q
from the string with p,q,r
and then use Function constructor to create an anonymous function with the new body (after replace).
jQuery('#btn_a').on('click', function(){
var onclickB = jQuery('#btn_b').attr('onclick'),
onclickA = Function(onclickB.replace("p,q", "p,q,r"));
return onclickA();
});
Note: you can do anything with this approach, just create a regex pattern to replace anything with what you want.
You need to make the function doSomething like below, pass null for btn_b and pass value for btn_a. Hope this helps.
HTML
<input type="button" id="btn_a">
<input type="button" id="btn_b">
SCRIPT
$("#btn_a").on("click", function() {
return doSomething(p,q,r);
});
$("#btn_b").on("click", function() {
return doSomething(p,q,null);
});
function doSomething(p,q,r){
if(r != null){
//do something for btn_a and return
} else {
//do something for btn_b and return
}
}
<input type="button" id="btn_a" onclick="return doSomething(p,q,r)">