使用JavaScript修改SelectField选择

时间:2019-05-05 10:41:42

标签: javascript python flask

我想根据字符串列表来渲染表单(使用Flask-WTForms)。此字符串列表指向DecimalField(s)以及选择SelectField参数中具有不同值的键。目标是渲染一个(或几个)DecimalField,例如Temperature,并在其旁边显示一个仅包含温度单位的SelectField。

这是选项的SelectField的元组列表以及将决定要呈现什么内容的字段的样子:

units_choices = [('temperature', '°C'), ('temperature', 'K'), ('temperature', '°F'), ('pressure', 'MPa'), ('pressure', 'bar'), ('pressure', 'psia'), ('fugacities', 'mol/l'), ('fugacities', 'mol/m3'), ('fugacities', 'g/ml'), ('fugacities', 'kg/m3')]
fields_to_show = ['temperature', 'pressure', 'fugacities']

这些是我的表单声明:

class UnitForm(FlaskForm):
    unit_field = FieldList(SelectField(label='', choices=units_choices))

class AnalysisForm(FlaskForm):
    temperature = DecimalField(label="Temperature")
    pressure = DecimalField(label="Pressure")
    fugacities = DecimalField(label="Fugacities")
    units = FieldList(FormField(UnitForm))

这是我的动态视图功能,可以通过相同的键来选择units_choices:

@app.route('/units/<field>') 
def units(field):
    units_choices_new = [ (key, value) for (key, value) in units_choices if (key == field) ]
    units_array = []
    for unit in units_choices_new:
        unit_dict = {}
        unit_dict['key'] = unit[0]
        unit_dict['value'] = unit[1]
        units_array.append(unit_dict)
    return jsonify({'units': units_array})

这是我的HTML渲染和JS代码:

<div class="container">

    <form method="POST" class="form" role="form">
        {{ form.csrf_token }}
        {% for i in form.units %}
            {{ i.csrf_token }}
            {% for j in i.unit_field %}
                {{ wtf.form_field(j) }}
            {% endfor %}
        {% endfor %}
    </form>    

    <script>
        const field_select = {{ fields_to_show|safe }};

        for (let i=0; i < field_select.length; i++) {

            let field = field_select[i];
            let units_select = document.getElementById('units-'+i+'-unit_field-0');
            console.log(field); //print temperature, pressure and fugacities


            window.onload = function() { 

                fetch('/units/' + field).then(function(response) {
                    alert(field); //only shows fugacities :(
                    response.json().then(function(data) {
                        let optionHTML = '';                        
                        for (let unit of data.units) {
                            optionHTML += '<option value="' + unit.key + '">' + unit.value + '</option>';
                        }
                        units_select.innerHTML = optionHTML;
                    })     
                });
            }
        }

    </script>   
</div>

我几乎使它工作了(它对一个字段有效),但是当将两个或多个字段字符串添加到fields_to_show列表中时,只有最后一个承诺成立,即,对于本示例,仅紧急状态的SelectField被更新为其实际单位。

0 个答案:

没有答案