0

Let's take a dictonary:

mydict = {
  'color': "blue",
  'brand': "Ford",
  'year': 1969
}

We pass this dict to our template, then, in the template, we have a select list with options according to our dictionary keys (color, brand, year).

Now, I want to change some text in my rendered template regarding the selected option.

So we have some Jquery that is getting the value of the selected option, like this:

$('#myselect').change(function() {
        var selected = $( "#myselect option:selected" ).text();
    });

Now that we have the selected text, I would like to use it as a key to display a value from our dictionary. Something like this

$('#myselect').change(function() {
            var selected = $( "#myselect option:selected" ).text();
            $('#mytext').text('{{ mydict.selected }}');
        });

But I guess mixing Django var and JS var like this, is not going to work... Any idea how I can do this ?

Fumble
  • 121
  • 2
  • 10
  • 1
    You can use html5 dataset attribute and get the value via JavaScript/jQuery. That's the cleanest method if you ask me. – Martins Mar 17 '21 at 11:16
  • Best to try something like this https://stackoverflow.com/a/25538871/1638231 – ziggrat Mar 17 '21 at 11:25

1 Answers1

0

Based on Martins comment, here is what I did:

In the template:

<select id="myselect">
  <option value="color">color</option>
  <option value="brand" selected="">brand</option>
  <option value="year">year</option>
</select>

{% for key,value in mydict.items %}
  <small id="{{key}}" class="messages" style="display:none;">
    {{ value }}
  </small>
{% endfor %}

Then some JS:

$('#myselect').change(function() {
        var selected = $( "#myselect option:selected" ).text();
        $('.messages').hide();
        $('#' + selected).show();

    });
Fumble
  • 121
  • 2
  • 10