Just write very nearly that code without eval
, there's nothing there that needs it:
var funVal = function() {
alert("a");
};
var Button1 = document.getElementById("BtnSave");
Button1.onclick = funVal;
In the comments you've said that the code is dynamically-generated server-side. That's not a problem at all, just have the server output the code where JavaScript code is expected (inside <script>...</script>
tags, or as the full content of a response you'll load via <script src="..."></script>
). The key in either case is to make sure that what you send to the browser is valid code.
Example 1: Dynamically-generated inline script
tag (you haven't said what the server-side technology is, so I went with the fairly-common PHP):
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Inline Dynamically Generated Script</title>
</head>
<body>
<p>Each time you load this page, the script in the inline
<code>script</code> tag at the end is different.</p>
<button id="theButton">Click Me</button>
<script>
document.getElementById("theButton").onclick = function() {
alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};
</script>
</body>
</html>
Live Example
Example 2: Dynamically-generated script in separate file:
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Dynamically Generated Script from File</title>
</head>
<body>
<p>Each time you load this page, the script in the file
loaded by the <code>script</code> tag at the end
is different.</p>
<button id="theButton">Click Me</button>
<script src="dynamic-script.php"></script>
</body>
</html>
JavaScript file (dynamic-script.php
):
<?php header('Content-type: application/javascript'); ?>
document.getElementById("theButton").onclick = function() {
alert("<?php echo("Hi there, this page's magic number is " . rand(0, 10000)); ?>");
};
Live Example