从JavaScript更改WTF表单选定字段中的选定值



我在我的网页上有三个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)
}

几个小时后才明白。可以设置"已选定";当你附加一个选项时标志为true。

所以对于你想要选择的一个选项,设置selected: true

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

最新更新