Dynamic form with Javascript in Django project

Good morning,

I am working on a template for a Django project and I would like to create a dynamic form, and so, according to a result in the drop-down menu, I display different div blocks. So I tried as I knew with a small javascript script but it doesn’t seem to work, the initial drop-down menu hangs on a value, dynamic fields are displayed only once and never disappear or change afterwards.

I guess Django may be the source of the problem.
Am I making a mistake in my code?

Thanks in advance!

<select class="form-select" id="action_menu" onchange="action_disp()">
    <option selected>-</option>
    <option value="score">score</option>
    <option value="color">color</option>

<script type="text/javascript">
    function action_disp(){
        var action_menu = document.getElementById('action_menu');
        var selected_val = action_menu.options[action_menu.selectedIndex].value;
        var score = document.getElementById('score');
        var color = document.getElementById('color');

        if (selected_val = "score"){
            score.style.visibility = 'visible';
            color.style.visibility = 'hidden';
        }else if(selected_val = "color"){
            score.style.visibility = 'hidden';
            color.style.visibility = 'visible';
            score.style.visibility = 'hidden';
            color.style.visibility = 'hidden';


<div id="score" style="visibility:hidden" ></div>

<div id="color" style="visibility:hidden" ></div>

What makes you think that this is related to Django at all? Django runs on the server - it prepares the page and sends it to the browser. The JavaScript runs in the browser, not on the server.

Thank you for your answer.
Well, it’s a task I’ve already done outside of Django and it worked very well. Also my code here is mainly a copy-paste of a validated response in a forum.
As Django has a particular template management system, linked to urls and views, I wondered if there was a conflict between Javascript and Django.

But I’m glad that’s not the case. Do you see an error in my code that could explain my problem?

Remember that in both JavaScript and Python, “=” is an assignment operator, while “==” is the test for equality. (And, of course, JavaScript also has the “===” operator for strict equality.)

1 Like