2

I am wanting to build some simple modules to help my students learn javascript. I have made a set of functions that I would like for the student to be able to enter and then that function be executed. For example. I have a function that moves an image from 1 div to another called move(); I then have a text field where the user needs to type move(); When they click submit I want the code they wrote to be executed so they can see what it does.

I had a really hard time searching for this and was hoping someone could point me in the right direction. Thanks!

<body>
    <textarea id='userInput'></textarea>
    <div id='go'>Go</div>
    <div id='canvas'>
        <div id='r1c1' class='square'><img src='dog.png' id='dog'></div>
        <div id='r1c2' class='square'></div>
    </div>
</body>
</html>
    <script>
    $('document').ready(function(){
    $('#go').click(function(){
        var code = $('#userInput').val();
        EXECUTE code; //This is where I want the code to be executed//
    });
});

function move(){
    $('#dog').appendTo('#r1c2');
};

1
  • Are you aware of jsfiddle.net ? Commented Apr 18, 2014 at 2:07

2 Answers 2

1

You can use eval() for this purpose (on w3Schools)

To take this even further, you can wrap the code in a try catch block to handle user errors.

Sign up to request clarification or add additional context in comments.

2 Comments

@RyanY If you believe this is your answer, you can mark it using the icon below rating.
Thanks, I will, just have to wait 3 more minutes :)
0

You can also use the console with most browsers to execute javascript. Hit F12 to load up the developer tools on all of the browsers. Click on the console tab. Type javascript until your heart's content.

One advantage to this method is that you should be able to execute any code that is included on the page.

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.