Phillip Senn
Phillip Senn

Reputation: 47605

Allow the user to change their own JavaScript

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

Answers (2)

Oriol
Oriol

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

Spikeh
Spikeh

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

Related Questions