简体   繁体   中英

Editing form data before passing into flask app

I have the following multiple selection form which is rendered by a flask app:

<form method="POST" action="">
    <label for="sports">Sports:</label>
    <select id="sports" name="sports" multiple>
        <option value="Basketball">Basketball</option>
        <option value="Football">Football</option>
        <option value="Baseball">Baseball</option>
        <option value="Golf">Golf</option>
        <option value="Soccer">Soccer</option>
    </select>
    <input type="submit" name="send" onclick="var selected_sports = project.getSelectedValues(document.querySelector('#sports'));">
</form>

I'm trying to send the data in the form of a list to the server / python code.

For example, if you select Basketball, Football and Golf the list will be ["Basketball", "Football", "Golf"] and if you select only Football the list will be ["Football"] .

I'm able to create the list using javascript (code below) but I'm not sure how to pass this created list to the server (the server is receiving only the first selected option).

JS code to create list of selected values (called in HTML form when submit button is clicked):

project = {};

project.getSelectedValues = function (selectTag) {
    var result = [];
    var options = selectTag && selectTag.options;

    for (var = 0; i < options.length; i++) {
        if (options[i].selected) {
            result.push(options[i].value || options[i].text);
        }
    }
    return result;
}

the server is receiving only the first selected option

You can submit the <select id="sports" name="sports" multiple> normally (without using JS to create a list) and reference all of the selected options in your python code by using getlist()

sports = request.form.getlist('sports')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM