Reputation: 47605
I'm teaching students how to write JavaScript, so I've got this on the page:
<textarea name="PgmJS">console.log(1);</textarea>
<script id="PgmJS">
</script>
What I'd like to do is:
$('textarea[name=PgmJS]').on('keyup',PgmJSKeyUp);
function PgmJSKeyUp() {
$('#PgmJS').text('function init() {' + $(this).val() + '}');
init();
}
But the browser is saying that init() is not defined.
Upvotes: 0
Views: 56
Reputation: 288100
It doesn't work this way, you need the evil eval
:
function PgmJSKeyUp() {
eval($(this).val());
}
You could also use Function
, setTimeout
or setInterval
(if you clear it), which are as evil as eval
when used with strings.
Or, if you really want to use <script>
element,
function PgmJSKeyUp() {
var $s = $('<script type="text/javascript">');
$s.text($(this).val());
$('body').append($s);
}
But keep in mind that JS code inside <script>
elements is only executed when they are added to the document.
Upvotes: 5
Reputation: 3695
That's because you're specifying the init function inside the textarea's text property - which by default, does not get picked up by the browser's JS compiler.
You will need to define the init function as normal JS code, and execute the custom JS code inside it. I smell an eval() coming on (ugh!) :|
Upvotes: 2