выберите раскрывающийся список показывает последнее значение первым - PullRequest
0 голосов
/ 14 марта 2019

У меня есть два четырех dropdown s, выбрано второе dropdown, и если я выберу первое dropdown, второе dropdown заполняет значение, но показывает первый элемент первым вместо первого

   sample data get the dropdown values
   var countrydata ={
    countries:[{
        "country_code": "TH",
        "country_name": "Thailand",
        "currency_from": [
            "THB",
            "USD"
        ],
        "currency_to": [
            "THB"
        ],
        "popular_to": [
            "Malaysia",
            "Myanmar"
        ],
        "name": {
            "en": "Thailand",
            "th": "ประเทศไทย"
        },
        "normalized_name": {
            "en": "thailand"
        }
    },
    {
        "country_code": "SG",
        "country_name": "Singapore",
        "currency_from": [
            "SGD",
            "USD"
        ],
        "currency_to": [
            "SGD"
        ],
        "popular_to": [
            "India",
            "United States"
        ],
        "name": {
            "en": "Singapore",
            "fr": "Singapour",
            "zh": "新加坡"
        },
        "normalized_name": {
            "en": "singapore"
        }
    }]
   }
   var currencydata = {
       currencies:[{
        "currency": "SGD",
        "country_code": "SG",
        "country_name": "Singapore",
        "name": {
            "en": "Singapore Dollar",
            "fr": "Dollar Singapour",
            "zh": "新加坡元"
        },
        "default_amount": "1000"
    },
    {
        "currency": "THB",
        "country_code": "TH",
        "country_name": "Thailand",
        "name": {
            "en": "Thailand Baht",
            "th": "เงินบาทไทย"
        },
        "default_amount": "9000"
    },
   }]}
   
   index.js file sample
   
   updateSendCountry(value) {
    this.sendvalue = this.countrydata.countries.filter(function (item) {
      return item.country_code == value;
    })
    if (this.sendvalue && this.sendvalue[0].currency_to) {
      var sendcurrency = this.sendvalue[0].currency_to[0];
      this.updateSendCurrency(sendcurrency);
    }
   }
    updateSendCurrency(e) {
    this.ccyvalue = this.currencydata.currencies.filter(function (item) {
      return item.currency == e;
    })
  }
   <select name="send_country" class="form-control" id="send_country" @change="${this.sendcountryChange}">
                           ${this.countrydata.countries.map((country, key) => html`<option value=${country.country_code}>${country.country_name}</option>`)}
                        </select>
                      </div>
                      <div class="input-group p-2">
                        <div class="input-group-prepend">
                          <select name="sccy" class="form-control" id="sccy" @change="${this.updateSendCurrency}">
                          ${this.sendvalue.map((currency) => currency.currency_from.map((send) =>
                            html`<option value=${send}>${send}</option>`))
                          }                          
                         </select>

Например:

Dropdown A -> Singapore  populates Dropdown B -> SGD, USD
Dropdown A -> Thailand  populates Dropdown B -> THB, USD
if dropdown A selection shows Singapore, SGD USD in Dropdown B
if USD selected in Dropdown B then i change Dropdown A to thailand it Dropdow B 
populates THB, USB but shows USD first(second option) rather than THB

1 Ответ

0 голосов
/ 18 марта 2019

this.sendvalue.map(...) обновит состояние (атрибуты и содержимое) элементов <option>, но не обязательно заменит их. Это означает, что при изменении списка текст первой опции будет изменен с SGD на THB, но вторая опция (USD) все равно будет выбрана.

Если вы хотите контролировать состояние выбора, вам нужно сохранить его и использовать что-то подобное для шаблона элемента:

this.sendvalue.map((currency, index) => currency.currency_from.map((send) =>
    html`<option value=${send} ?selected=${index === selectedIndex}>${send}</option>`))

Здесь я использую переменную selectedIndex для хранения выбранного индекса. Вам придется сбросить его при смене страны.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...