jQuery execute string as function

11,317

Solution 1

You could use the eval-function on the client-side:

This will execute your javascript immediately:

eval('$("textArea").attr("disabled","true")');

But, as said in the comments, be careful with what you do as this is a very crude method.

Also, in terms of security, you don't really gain anything, because one could still open the dev-tools and remove the disabled attribute

Solution 2

Alternatively, you could break your string up into multiple strings passed from the server. For example:

// variables passed from the server
selector = 'textArea';
method = 'attr';
arguments = ['disabled', 'true'];

Then you could evaluate it this way:

$(selector)[method](arguments[0], arguments[1]);

Of course, if the number of arguments needs to be dynamic it would get a bit trickier.

Share:
11,317
Shazboticus S Shazbot
Author by

Shazboticus S Shazbot

I smell like bacon.

Updated on June 28, 2022

Comments

  • Shazboticus S Shazbot
    Shazboticus S Shazbot almost 2 years

    I want to pass in a jQuery command (in the form of a string) from server-side JS to client-side js. This allows me to modify client-side DOM stuff from the server-side.

    Function:

    $("textArea").attr("disabled","true");
    

    What I want to do:

    $['$("textArea").attr("disabled","true")']();
    

    Throws an error. Thoughts?