【问题标题】:Change selected value in WTF form selected field from JavaScript从 JavaScript 更改 WTF 表单选定字段中的选定值
【发布时间】:2021-10-10 04:25:09
【问题描述】:

我的网页上有三个 WTF 表单选择字段,它们是依赖的 - 即第一个选择的字段是国家,第二个是州,第三个是城市。到目前为止,我已经设法让它们变得可靠,因此如果你选择美国,它只会显示美国等州。

但是,一旦用户选择了一个国家,我想将州的默认值设置为美国最大的州,然后是该州最大的城市。

不知何故,我无法找到任何有关如何从 JS 设置 WTF 表单选定字段的当前值的文档。

所以问题是:我不知道如何访问该字段并更改值。

//the country_w_states is a dict with the countries as keys and states as lists (parsed from server) 

//triggered when user selects a country
$(".country-changed").change(function(){
update_state()
});

//update associated states
function update_state() {
    var country = $('#selected_country').val()
    
    var country_w_states = {{ country_w_states|tojson}};
    $('#selected_state').empty();
    country_w_states[country].forEach(function(item) {
            $('#selected_state').append(
                $('<option>', {
                    text: item
                })
            );
        });
    //How to set the selected/default value of the state field?
    //Something like the below...
    //$('#selected_state').default() = largest_city[country] 


    update_city() //update city based on state - same methodology as above (omitted since not really relevant for question)
}

【问题讨论】:

    标签: javascript flask-wtforms


    【解决方案1】:

    几个小时后想通了。 附加选项时,可以将“已选择”标志设置为 true。

    因此,对于您希望选择的一个选项,设置 selected: true

    $('<option>', {
                    value: item,
                    text: item,
                    selected: true
                })
    

    【讨论】:

      猜你喜欢
      • 2016-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-31
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      相关资源
      最近更新 更多