JavaScript,Bootstrap selectpicker,在其他更改时保持选择状态

时间:2019-07-30 13:46:08

标签: jquery bootstrap-selectpicker

当第一个选择更改时,我要保留第二个选择的选项。我做了一个jsfiddle来使用它:

http://jsfiddle.net/pmiranda/yeh6b83s/40/

$(document).ready(function() {
    // I'll give and empty array, because I will assume that at first is has no data on database
    let values = [];
    if(1 /* Originally here are some js conditions*/) {
        getAL1ByCountry(values);
    } 
    $('#adm_l_1').on('change', function() {
      getAL3ByAL1(values);
    });
    $('#adm_l_1').change();
});

// This functions works with ajax but now I'm just giving some arrays of objects to make the example    
function getAL1ByCountry(value) {
  let data = {'data': [{'id': 1, 'name': 'Chile'}, {'id': 2, 'name': 'USA'}]};
  console.log(data);
  $.each(data.data, function (k, v) {
    console.log(v);
    var _selected = false;
    $.each(value, function (k2, v2) {
      if (v2.id == v.id) _selected = true;
    });

    if (_selected)
      $('#adm_l_1').append('<option value="' + v.id + '" selected>' + v.name + '</option>');
    else
      $('#adm_l_1').append('<option value="' + v.id + '">' + v.name + '</option>');
  });
  $('#adm_l_1').selectpicker('refresh');

  $('#adm_l_1').change();
}

function getAL3ByAL1(values) {
  $('#adm_l_3').empty();
  // Now I will assume that an ajax call was succes and it gives me this data:
  /*$.ajax({
                  url: '/getAL1ByCountry',
                  method: 'POST',
                  data: {
                      country   : country_id
                  }
              }).done(function (data) {
        */
  let data = {
    'data': [
      {'id': 1, 'name': 'A'},
      {'id': 2, 'name': 'B'},
      {'id': 3, 'name': 'C'},
      {'id': 4, 'name': 'D'},
      {'id': 5, 'name': 'E'},
    ]
  };
  $.each(data.data, function (k, v) {
    console.log('data', data);
    var _selected = false;
    $.each(values, function (k2, v2) {
      if (v2 == v.id) _selected = true;
    });
    if (_selected)
      $('#adm_l_3').append('<option value="' + v.id + '" selected>' + v.name + '</option>');
    else
      $('#adm_l_3').append('<option value="' + v.id + '">' + v.name + '</option>');
  });
  $('#adm_l_3').selectpicker('refresh');
}

第二个选择更改第一个的值。在示例中尚不清楚,但想法是:

“如果我更改了第一个选择的值,请不要删除第二个选择的值”

该库有一个empty()方法,因为没有它,每次选择一个选项时,它将加载这种情况:

(如果我选择A) 一种 (如果我选择B) AAB (如果我选择C) AABABC

有帮助吗?

1 个答案:

答案 0 :(得分:0)

好的,您的问题涉及以下部分:

$.each(values, function (k2, v2) {
    if (v2.id == v.id) _selected = true;
}

values始终为空,并且永不供稿。 因此,您可以将所选内容的当前值保存在这样的临时变量中:

let saved = $('#adm_l_3').val();

并重新设计算法以使用它代替values

$.each(data.data, function (k, v) {
    var _selected = v.id == saved;

    if (_selected)
        /* your code */
}

http://jsfiddle.net/vksw8e9t/6/