Reputation: 7121
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!
Upvotes: 1
Views: 73
Reputation: 2596
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;
Upvotes: 1