【发布时间】: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)
}
【问题讨论】: