2

I want to get user-input from text-area and pass it to my Javascript function with the following code but can't make it work. Could anybody help me with this?

<!DOCTYPE html>

<head>
    <title>Testing</title>
    <script type="text/javascript">
    function MyFunc(UserCode.value) {
        var syntax = esprima.parse(UserCode.value);
        document.getElementById("demo").innerHTML = JSON.stringify(syntax);
    }
    </script>
    <script src="esprima.js"></script>
    <script src="parse.js"></script>
</head>

<body>
    <label>Please enter your code:</label>
    <br>
    <textarea rows="4" cols="50" id="UserCode">
var answer = 6 * 7;
    </textarea>

    <br>
    <button type="button" onclick="MyFunc(UserCode.value)">Convert</button>
    <p id="demo">Result</p>
</body>

</html>

3 Answers 3

1

First of all, you are trying to access your textarea element incorrectly. You must use document.getElementById, like so:

<button type="button" onclick="MyFunc(document.getElementById('UserCode').value)">Convert</button>

Second, you are defining your function incorrectly. Your function should look something like this:

function MyFunc(text) {
    var syntax = esprima.parse(text);
    document.getElementById("demo").innerHTML = JSON.stringify(syntax);
}
Sign up to request clarification or add additional context in comments.

Comments

0

UserCode is not defined in your code. Creating an element with an id does not make a javascript variable with that name magically. You've got to get a reference to the element the same way you do with the demo paragraph:

<!DOCTYPE html>

<head>
    <title>Testing</title>
    <script type="text/javascript">
    function MyFunc(textAreaId) {
        var value = document.getElementbyId(textAreaId).value;
        var syntax = esprima.parse(value);
        document.getElementById("demo").innerHTML = JSON.stringify(syntax);
    }
    </script>
    <script src="esprima.js"></script>
    <script src="parse.js"></script>
</head>

<body>
    <label>Please enter your code:</label>
    <br>
    <textarea rows="4" cols="50" id="UserCode">
var answer = 6 * 7;
    </textarea>

    <br>
    <button type="button" onclick="MyFunc('UserCode')">Convert</button>
    <p id="demo">Result</p>
</body>

</html>

1 Comment

Thanks a lot!! I really like this one but somehow not working in my machine
0

Example: http://jsfiddle.net/3ackg/

JS:

$("#convert").click(function() {
    var code = $('#code').val();
    //var code = esprima.parse(code);
    var result = JSON.stringify(code);
    $('#result').html(result);
});

HTML:

<textarea rows="4" cols="50" id="code">var answer = 6 * 7;</textarea>
<button type="button" id="convert">Convert</button>
<p id="result">Result</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.