1

I want to call the javaScript function defined inside the same template in Django. How can I do it?

{% extends 'base.html' %}

{% block content %}

        {% if error %}
            showAlert()
        {% endif %}

    <script> function showAlert() {alert ("Please select at least one option");}</script>
{% endblock %}

I want to call showAlert() if there is error present. I have handled the error in the view. I do not a method about how to call the function here? It is showing the function name.

7
  • 2
    Bear in mind that the template is rendered on the server using Python; alert is available in the browser in JavaScript. Commented Sep 7, 2019 at 9:32
  • Oh! yeah!! Got it..... but how can I do this? Loading a JS file or what else? Commented Sep 7, 2019 at 9:36
  • You're already showing how to use JavaScript - <script> blocks. Commented Sep 7, 2019 at 9:37
  • But how am I supposed to call this? This is not working.... Commented Sep 7, 2019 at 9:38
  • if you open the browser console, you may see an error like "ReferenceError: showAlert is not defined", just move the definition of the function on top. and also call <script> showAlert() </script> Commented Sep 7, 2019 at 9:41

1 Answer 1

2

You can call the javascript function inside the <script> tag

{% extends 'base.html' %}

{% block content %}

    <script> 
      function showAlert() {
            alert ("Please select at least one option");
      }
    </script>

    {% if error %}
    <script>
        showAlert()
    </script>
    {% endif %}
{% endblock %}

Or you can put {% if ... %} statement inside <script> tag

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

1 Comment

Thanks for helping out buddy but the problem is that it does not let the page to load until clicked okay.

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.