1

I get a variable from the controller that is a java script code and want to init a variable of java script file with this data as a string.

What I mean is:

Model.TrialScript is equal to the string of:

<script type="text/javascript">var j = new Date();</script>

(I got it from the DB)

and then, I want to do the next thing in my js file:

var TrialScript = '<%= Model.TrialScript %>';

The problem is that TrialScript is not like I expect:

var TrialScript = '<script type="text/javascript">var j = new Date();

assuming I must get the js code as: <script type="text/javascript"> and not: <script type=\"text/javascript\">, how can I solve this issue?

Another thing may helps: I want to run this script only when the user press a button (is called: button1)

Maybe is there an option to call this script from the js after the button is clicked without saving this script as a variable?

any help appreciated!

8
  • 1
    The escaping is normal. Commented Sep 21, 2014 at 11:03
  • @Scunibster, thank you.. I know but how can I get the full js code? or maybe is there an option to call this script from the js after the button is clicked without saving this script as a variable? Commented Sep 21, 2014 at 11:05
  • You should have a look at the eval function. w3schools.com/jsref/jsref_eval.asp Commented Sep 21, 2014 at 11:06
  • @mainguy, I know it but it doesnt get js code: <script type...> Commented Sep 21, 2014 at 11:08
  • 2
    Leave out the <script type...> part. Just use the code. Commented Sep 21, 2014 at 11:09

1 Answer 1

1

You can try that way:

var TrialScript = '<%= Model.TrialScript %>';
//remove script tags, get only the code
TrialScript = TrialScript.replace(new RegExp("^<script.*?>(.*)</script>"), "$1");
// transform the code as a JS function
TrialScript = new Function(TrialScript);
// associate to the button1
document.getElementById("button1").onclick = TrialScript;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.