Flask jinja2 retrieve value of dropdown list

Viewed 865

I'm using Flask with Jinja2 templates, how can I retrieve value from a select box using Jinja2 or using Java script + Jinja2 variable and use it?

Python side:

@app.route('/')
def dependent():
    fruits= {'apple':100,'orange':80,'mango':200}
    return render_template('select.html',fruits=fruits)

HTML+Jinja2 side

<form>
<select name="fruit" id="fruit">
    {% for fruit in fruits.keys() %}
        <option value="{{ fruit }}"> {{ fruit }} </option>
    {% endfor %}
</select>

<p>fruits[{{fruit}}]</p>

</form>

I would like to display the price of the selected fruit next to the selection but I'm unable to retrieve the selected value and use it. I know the final '< p>' tag is incorrect. How to do this properly?

PS: I'm completely ignorant regarding JS, jQuery and Ajax

Update:

<script>
          var selectTag = document.getElementById('fruit')
          var pTag = document.getElementById('fruit-binding')
          function val() {
            pTag.innerText = fruits[selectTag.value];
        </script>
1 Answers

You could try something like this using javascript. One way to do it, to add your fruit price as the value of the option tag, and use javascript to display this value of the selected item into the p tag.

<form>
  <select onchange="val()" name="fruit" id="fruit">
    {% for fruit in fruits %}
    <option value="{{ fruits[fruit] }}">{{ fruit }}</option>
    {% endfor %}
  </select>

  <p id="fruit-binding"></p>
</form>
<script>
  var selectTag = document.getElementById('fruit')
  var pTag = document.getElementById('fruit-binding')
  pTag.innerText = selectTag.value
  function val() {
    pTag.innerText = selectTag.value
  }
</script>
Related