nathannewyen
nathannewyen

Reputation: 253

How can I show select dropdown value in django template?

I'm trying to achieve how to get a dropdown value to change the data showing in my page:

Here's an photo from my page: enter image description here

here's my views.py: def index(req):

test = [
    {"name": "hello", "age": 30, "size": 100},
    {"name": "ewefef", "age": 12, "size": 32},
    {"name": "12d1", "age": 13, "size": 123},
    {"name": "dsf", "age": 54, "size": 324},
    {"name": "gfd", "age": 1, "size": 12},
    {"name": "vcb", "age": 3, "size": 3},
    {"name": "csd", "age": 4, "size": 1},
    {"name": "a", "age": 32, "size": 11},
    {"name": "wfwef", "age": 123, "size": 33},
]
context = {
    'test': test,
}

return render(req, 'index.html', context)

here is my template index.html:

<select name="pick" id="mySelect">
    <option value="name">name</option>
    <option value="age">age</option>
    <option value="size">size</option>
</select>

{% for i in test %}
<div id="demo">{{i.name}}</div>
{% endfor %}

I want to achieve when I select name it will show the name, and when I select age it will show only age... how can I do that?

Upvotes: 1

Views: 1239

Answers (1)

mprostak
mprostak

Reputation: 246

Here is an example of how you can add logic using javascript.

<select name="pick" id="mySelect">
    <option value="name">name</option>
    <option value="age">age</option>
    <option value="size">size</option>
</select>

<div id="name">
    {% for i in test %}
        <p>{{i.name}}</p>
    {% endfor %}
</div>

<div id="age" style="display: none;">
    {% for i in test %}
        <p>{{i.age}}</p>
    {% endfor %}
</div>

<div id="size" style="display: none;">
    {% for i in test %}
        <p>{{i.size}}</p>
    {% endfor %}
</div>

<script>

    let current = document.getElementById('name');

    function changeSelect (idDivName) {
        current.style.display = 'none';
        current = document.getElementById(idDivName);
        current.style.display = 'block';
    }

    document.getElementById('mySelect').addEventListener('change', function() {
        changeSelect(this.value);
    });

</script>

In the example it's in three different loops. You can also make in one loop, but then you would need to slightly change the logic.

You can find more information here: DOM Manipulation

Upvotes: 2

Related Questions