Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save onclick attribute value in a variable and then execute it

Tags:

jquery

I have some inputs (buttons). Their onclick function is added programmatically. I'd like to take their onclick function and to put it in a variable and do some function instead and then execute whatever it was in their onclick.

So far I managed to get their onclick function and put it in a variable and execute my code but now I have no idea how to execute the old onclick function that is in this variable.

var example = $(item).attr('onclick');
//do other stuff

P.S For some reason I can't use a pre-function to delay this onclick function from executing until my function is finished so I need my onclick function to save somewhere like the code above and then launch.

like image 705
Sara NikitaUsefi Avatar asked Jun 10 '26 08:06

Sara NikitaUsefi


1 Answers

onclick attribute has String value which you have saved in variable.
You can execute it as code using eval() function.

Fiddle example.

<div onclick="test();">test</div>

function test()
{
    alert(1);
}

$(function()
{
    eval($('div').attr('onclick'));
});
like image 183
Regent Avatar answered Jun 11 '26 20:06

Regent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!