Home > front end >  Send select2 value from dropdown to flask
Send select2 value from dropdown to flask

Time:02-16

I have a dropdown select2 field with 3 different values. But how can i send the selected value from the dropdown to a variable in my flask program? Here´s my following code and what i tried so far

<script type="text/javascript">
                //var hugo=document.getElementById("fmea").value;
                $(document).on('submit','#form',function(e)
                               {
                  e.preventDefault();
                  $.ajax({
                    type:'POST',
                    url:'/index',
                    data:{
                      event:$("#event").val(),
                      context:$("#context").val(),
                      //'fmea[]':$("#fmea.select2").val() 
                      //fmea:$('.test').select2(content[0]) 
                      fmea:JSON.stringify(fmea)
                    },
                    //traditional:true,
                    success:function()
                    {
           
                      draw();
                    }
                  })
                });
            </script>

select2

<script>
                var content = [
                    {id: 0, text: "Event1"},
                    {id: 1, text: "Event2 "},
                    {id: 2, text: "Event4"},
                ];
            
            
                $(".test").select2({
                     data:content,
                     // minimumInputLength: 2,
                     width: '35%',
                     multiple:true,
                     placeholder:"Enter another event",
                     // templateResult:formatState
            
                });

and the html code

<form method="post" id="form" enctype="multipart/form-data">
                                    <input type="text" name="event" id="event"  placeholder="Event" >
                                    <input type="text" name="context" id="context"  placeholder="Context" >
                                    <input type ="text" name="fmea" id="fmea"  placeholder="Select another Event">
                                    <br>
                                    <br>
                                    <button type="submit"  onclick="hide()" >Show Graph</button>                                    
</form>

and python

fmea=request.form.get("fmea")

I´m getting the first two input values easily, but the fmea tag returns None. If you could give me a hint how to get the selected value, I´d appreciate it very much.

CodePudding user response:

The example below shows you how to submit a form with a select box like yours to the server using AJAX.

As soon as a submit event is fired, the entire form is formatted accordingly via the serialize function and then sent.
Since you have chosen a variant of the selection field in which several options can be selected, the ImmutableMultiDict provided by the request.form object contains a list of tuples. In this case you can use request.form.getlist(...) to query the values contained using the name of the selection box, as you already know from other input fields. The return value corresponds to a list with the selected values. These are automatically converted by specifying the type parameter.

Flask (app.py)
from flask import Flask 
from flask import (
    render_template, 
    request, 
    jsonify
)

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/data', methods=['POST'])
def data():
    events = request.form.getlist('events', type=int)
    return jsonify(selected=events)
HTML (templates/index.html)
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Select2 Example</title>

    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
  </head>
  <body>
    <form name="my-form" method="post">
      <select name="events"></select>
      <button type="submit">Submit</button>
    </form>

    <output name="result"></output>

    <script
      src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
      crossorigin="anonymous"></script>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

    <script type="text/javascript">
      (function(uri) {
        $(document).ready(function() {
          const content = [
            {id: 0, text: 'Event 1'},
            {id: 1, text: 'Event 2'},
            {id: 2, text: 'Event 3'},
          ];
          $('select[name="events"]').select2({
            data: content,
            width: '35%',
            multiple: true,
            placeholder: 'Enter another event'
          });

          $('form[name="my-form"]').submit(function(evt) {
            evt.preventDefault();
            $.ajax({
              method: 'POST',
              url: uri,
              data: $(this).serialize()
            }).done(function(data) {
              $('output[name="result"]').html(data.selected.join(','));
            })
          });
        });
      })({{ url_for('.data') | tojson }});
    </script>
  </body>
</html>
  • Related