动态选择下拉列表基于在另一个的NodeJS下拉

问题描述 投票:-2回答:1

我有一个集合“国家”在MongoDB中。猫鼬架构如下:

{ 
id: number field(autoincrement by 1), 
short: //stores IN, US, UK 
Name: //stores India, United States, United Kingdom 
}

为前:

{_id: objectId, id: 1, short: "IN", name: "India"}
{_id: objectId, id: 2, short: "US", name: "United States"}
{_id: objectId, id: 3, short: "UK", name: "United Kingdom"}

在UI,我有两个下拉列表:短和国家。短期下拉被绑定到短期和国家下拉被绑定到国家收藏的名称字段。

现在,我的要求是:当我在短期下拉列表中选择“IN”,“印度应该在国家下拉菜单中选择。

任何人都可以请建议如何处理这一要求进行。

谢谢

javascript jquery
1个回答
0
投票

$(function () {
  $('#country').change(function() {
    const state = $('#state');
    state.empty();
    if (this.value) {
      getStates(this.value).then(function (states) {
        states.forEach(s => { state.append($(`<option>${s}</option>`)); });
      });
    }
  });
  
  function getStates(countryId) {
    // Returning a promise to simulate calling your node back end
    // Non mock should return $.get('states/' + countryId)
    return new Promise(function(resolve, reject) {
      resolve(
        countryId === '1' ? ['Andhra Pradesh', 'Arunachal Pradesh'] :
        countryId === '2' ? ['New York', 'New Jersey', 'Wasington', 'California'] :
        ['Bedfordshire', 'Berkshire']
      );
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
  <option value="">Please select</option>
  <option value="1">India</option>
  <option value="2">United States</option>
  <option value="3">United Kingdom</option>
</select><br>

<select id="state">
</select>
© www.soinside.com 2019 - 2024. All rights reserved.