0

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.

Deshwal
  • 2,461
  • 2
  • 17
  • 57
  • 2
    Bear in mind that the template is rendered on the server using Python; `alert` is available in the browser in JavaScript. – jonrsharpe Sep 07 '19 at 09:32
  • Oh! yeah!! Got it..... but how can I do this? Loading a JS file or what else? – Deshwal Sep 07 '19 at 09:36
  • You're already showing how to use JavaScript - ` – jonrsharpe Sep 07 '19 at 09:37
  • But how am I supposed to call this? This is not working.... – Deshwal Sep 07 '19 at 09: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 `` – PRMoureu Sep 07 '19 at 09:41
  • I did it earlier but the problem is that the page does not load until I press Ok on the the alert. That's why I moved it – Deshwal Sep 07 '19 at 09:44
  • maybe a popup alert is not the best, but you can also delay the opening with : `document.addEventListener('DOMContentLoaded', function(){ alert ("Please select at least one option"); }, false);` – PRMoureu Sep 07 '19 at 10:12

1 Answers1

1

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

Eby Sofyan
  • 394
  • 3
  • 7
  • Thanks for helping out buddy but the problem is that it does not let the page to load until clicked okay. – Deshwal Sep 07 '19 at 10:06