Reputation: 2065
I'm trying to attach a click event to a button that runs calls from both a parameter and from itself.
What I want is a 1st alert to always show, then execute the 2nd alert that is stored in myparam.onclick as a string.
Non-working attempt:
var myparam = { onclick: 'alert("second");' };
$('#my_button_id').on('click', function(){ alert('first'); myparam.onclick });
I know that if I change myparam to a legitimate function, such as:
var myparam = {onclick: function(){alert('second');} }
I can call that just fine by
$('#my_button_id').on('click', myparam.onclick);
but I still don't know how to concatenate two together. I don't want to call the first alert every time in the myparam func call.
Any help is appreciated.
Upvotes: 0
Views: 236
Reputation: 33726
You can use the eval
function to execute javascript code as String.
var myparam = {
onclick: 'alert("second");'
};
$('#my_button_id').on('click', function() {
alert('first');
eval(myparam.onclick);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<button id="my_button_id">Click</button>
Upvotes: 2
Reputation: 2855
If you really needed a string you can create a function and supply the body as a string then call it:
var myparam = { onclick: 'alert("second");' };
$('#my_button_id').on('click', function(){
alert('first');
var fun = Function(myparam.onclick);
fun();
});
Upvotes: 0
Reputation: 933
You should see that mate: https://stackoverflow.com/a/12651991/6158032
My little help is..
//Clousure
(function($) {
//Document.ready
$(function(){
//I think you want this ?
let myparam = { onclick: function() { alert("second"); } };
$('#my_button_id').on('click', function(){ alert('first'); myparam.onclick() });
//Another way.
function doAlert (messages) {
alert(messages);
}
//Params Object
let my_params = {
onclick_first : function () { return doAlert('first') },
onclick_second : function () { return doAlert('second') }
}
//Event Click
$('#my_button_id').on('click',function(){
//First Alert
my_params.onclick_first();
//Second Alert
my_params.onclick_second();
});
});
})(jQuery);
Upvotes: 0
Reputation: 19
It was close:
var myparam = {onclick: function(){alert('second');} };
$('#my_button_id').on('click', function(){ alert('first'); myparam.onclick() });
You missed a parenthesis at the end f the function call: myparam.onclick()
Upvotes: 0