views:

46

answers:

2

I need to call a jQuery function with EVAL (but I don't know how to do it), then I solve with this solution, but I don't think that this is the correct way...

<script>
jQuery.fn.customfunction = function (data) { alert( data ); }
</script>

<div id="eval_div"></div>
<form><input role="button" myFunction="customfunction"/></form>
<script>
$('[role=button]').click( function() {
var button = this;
$.post( "/action",
        $(form).serialize(),
        function (data) {
            $('#eval_div').html( "<script>" + $(button).attr('myFunction')  + "('" +  data   + "');</script>" );
        } );
});
</script>

customfunction is a general function for each form, each form has a different CUSTOMFUNCTION with different name, by this reason, the button has the name of the function.

+2  A: 

You don't need eval in this case. In JavaScript you can use dot notation or square brackets. They mean the same thing. Try this line.

$('#eval_div').html(jQuery.fn[$(button).attr('myFunction')](data));
gradbot
YEAH! THANKS! :)
Cris Hong Kong CRISHK
+1  A: 

If you just want to call the function... you can do it very simply:

function (data) {
    jQuery.fn[$(button).attr('myFunction')](data);
};
Claudiu
YES:) thank you!
Cris Hong Kong CRISHK