0

I am trying to create a form in Flask whereby when a user clicks on an object in a table a readonly form is populated with the value related to that object.

The problem I am having is when I pass that content value {{user.content}} to the Javascript that will update the form I am getting an error Uncaught ReferenceError: foo is not defined, where foo == user.content.

Not sure what is going on here besides my value being passed as a variable object and not a string. I have tried casting to a string like so:

onclick="displayResponse({{user.content|string}})"

But that does not seem to make any difference. Any idea how I can correct this?

The JS itself is correct, if I hardcode the value the form updates fine.

<div class="form-group">
    <label for="exampleFormControlTextarea1">Response Data</label>
    <textarea class="form-control" id="response-form-output" placeholder="root" rows="3" readonly></textarea>
  </div>


{% for user in users %}
<tr>
    <td>
        <button type="button" class="btn btn-primary" onclick="displayResponse({{user.content}})">{{user.name}}</button>
    </td>
    <td>
        {{user.content}}
    </td>
    <script type="text/javascript">
        function displayResponse(data) {
            document.getElementById("response-form-output").value=data;
        }
    </script>
</tr>
{% endfor %}

1 Answer 1

1

Jinja2 does not aware of the actual context of the variable, it just replaces the variable with its value. It's your job to make sure that the resulting source code has correct syntax. In your case the displayResponse JS function expect a string parameter, so we need to produce one:

<button type="button" class="btn btn-primary" onclick="displayResponse('{{user.content}}')">{{user.name}}</button>

If user.content is e.g. "test string", then this becomes: displayResponse('test string'). Without the apostrophes, JS try to get the non-existing test and string variables. Make also sure that you replace every apostrophe in user.content with the respective HTML entity, otherwise it will produce a syntax error.

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

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.