簡體   English   中英

在select2插件Javascript或jquery中交換兩個選擇框的值

[英]Swap values of two select boxes in select2 plugin Javascript or jquery

我使用select2插件創建了兩個選擇框,每個選擇框都有不同的國家名稱和標志圖像,並且從下面的數據庫中獲取值是代碼。

JS代碼

$(".currencyconverterselect").select2({
  templateResult: addflag,
  templateSelection: addflag
});

function addflag(opt) {
  if (!opt.id) {
    return opt.text;
  }
  var $opt = $(
    '<span><img src="./img/flags/' + $(opt.element).attr('data-country-code') + '.png" class="userPic" /> ' + $(opt.element).text() + '</span>'
  );
  return $opt;
};

HTML代碼

    <label style="color:white">Currency from</label>
              <select name="fromcurrency_cc" id="fromcurrency_cc" class="form-control charts_currency" style="width:100%" required="required">
                <?php
$sql = "SELECT fc.country_id,fc.code,fc.name,cc.country_code AS countrycode FROM fx_currency fc LEFT JOIN fx_country cc ON fc.country_id = cc.id ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {

    if ($row['code'] == 'AED')
    { ?>
                <option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>" selected>
                  <?php echo $row['name']; ?>(
                  <?php echo $row['code']; ?> )</option>
                <?php } else { ?>

                <option data-country-code='<?php echo $row['countrycode']; ?>' value="<?php echo $row['code']; ?><?php echo $row['countrycode']; ?>">
                  <?php echo $row['name']; ?>(
                  <?php echo $row['code']; ?> )</option>

                <?php }}
} else {
  echo "0 results";
}
                ?>
              </select>

我還創建了一個按鈕,下面是代碼

<a href="#" id="swapvalues_btn1" style="color:white" ><i class="fa fa-exchange fa-2x"></i></a>

我想通過單擊按鈕將FROM貨幣的值交換為TO Currency,反之亦然。

我試過下面的代碼

$("#swapvalues_btn1").on('click', function() {
    var pickup = $('#fromcurrency_cc').val();
    $('#from').val($('#tocurrency').val());
    $('#to').val(pickup);

  });

Select2將偵聽附加到它的change事件。 如果進行了需要反映在Select2中的任何外部更改(例如更改值)。

只需使用下面的代碼

$("#swapvalues_btn1").on('click', function() {
      var fromcurrency =  $('#fromcurrency').val();
      var tocurrency = $('#tocurrency').val();
      $('#fromcurrency').val(tocurrency).trigger('change');
      $('#tocurrency').val(fromcurrency).trigger('change');
});

有關更多信息, 單擊鏈接https://select2.github.io/options.html#events

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM