Скрытая optgroup динамически после выбора - PullRequest
2 голосов
/ 07 февраля 2020

У меня есть 2 optgroup в моем списке выбора (категория и подкатегория) , и я пытаюсь показать optgroup и скрыть другое при выборе подкатегории.

например, если я выбираю в категория (спорт, музыка c) в подкатегории Я отображаю только спорт и музыку c

Я пробовал использовать следующий код, но он не работает

Спасибо

$("#custom_form_names_category").on("change", function() {
  var selectedVal = $(this).find("option:selected").text();
  console.log(selectedVal);
  $('#custom_form_names_subcategorie > [aria-label="' + selectedVal + '"]')
    .show()
    .siblings("optgroup")
    .css("display", "none");
});

$(".js-select2").select2({
  closeOnSelect: false,
  allowClear: true,
  tags: true,
  dropdownCssClass: "beforecheckbox"

});
.select2.select2-container {
  width: 100% !important;
}

.select2-container .select2-selection__rendered {
  padding: 5px 15px 0 15px;
  text-transform: uppercase;
  font-size: 13px;
  box-shadow: none;
  background-image: none;
  text-transform: uppercase;
  font-size: 13px;
}

.select2-container .select2-selection--single {
  height: 100% !important;
  border-radius: 15px !important;
}

.beforecheckbox .select2-results__option[aria-selected=true]:before {
  content: "";
  color: #fff;
  background: url(../images/svg/check_active.png);
  border: 0;
  display: inline-block;
  padding-left: 3px;
}

.beforecheckbox .select2-results__option[aria-selected=true]:before {
  content: "";
  display: inline-block;
  position: relative;
  width: 1.5rem;
  height: 1.5rem;
  background-color: #fff;
  margin-right: 20px;
  vertical-align: middle;
  right: 0;
  float: right;
}

.beforecheckbox .select2-results__option[aria-selected=false]:before {
  content: "";
  display: inline-block;
  position: relative;
  width: 1.5rem;
  height: 1.5rem;
  border: #b7b9cc solid 2px;
  background-color: #fff;
  margin-right: 20px;
  vertical-align: middle;
  right: 0;
  float: right;
}

.beforecheckbox .select2-results__option[aria-selected=true]:before {
  background: red;
}

#custom_form_names_category {
  margin-bottom: 50px !important;
}

.select2.select2-container {
  margin-bottom: 50px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.full.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<select id="custom_form_names_category" multiple class="js-select2 small-select addplaceholderslect select2-hidden-accessible" tabindex="-1" aria-hidden="true">
  <option value="1" data-select2-id="25">Sport</option>
  <option value="17" data-select2-id="26">Volley</option>
  <option value="18" data-select2-id="27">Musci</option>
  <option value="29" data-select2-id="28">film</option>
  <option value="35" data-select2-id="29">Englich</option>
</select>

<select id="custom_form_names_subcategorie" multiple class="js-select2 small-select addplaceholderslect select2-hidden-accessible">
  <optgroup label="Sport" data-select2-id="33">
    <option value="2" data-select2-id="34">Dance </option>
  </optgroup>
  <optgroup label="Musci" data-select2-id="35">
    <option value="3" data-select2-id="36">Catégorie 4</option>
    <option value="4" data-select2-id="37">Rap</option>
  </optgroup>
  <optgroup label="Volley" data-select2-id="38">
    <option value="5" data-select2-id="39">Catégorie 4</option>
  </optgroup>
  <optgroup label="film" data-select2-id="40">
    <option value="7" data-select2-id="41">Catégorie 5</option>
  </optgroup>
</select>

1 Ответ

1 голос
/ 07 февраля 2020

Вы не можете взаимодействовать с группами опций, Вы можете только отключить их, но с обработанным результатом select2.

test:

$('#custom_form_names_subcategorie').on('select2:open', function (e) {
//var first = $('#custom_form_names_category').find(':selected');
//console.log(first);
setTimeout(function(){
    $('[aria-label]').hide();
    $('#custom_form_names_category').find(':selected').each(function( index ) {
        var selected = $( this ).text();
        console.log( index + ": " + selected );
        $('[aria-label="' + selected + '"]').show();
        console.log($('[aria-label="' + selected + '"]'));

    });
},100);
//$('[aria-label="' + selectedVal + '"]').show().siblings("li").css('display', 'none');

});

Это также работает, когда вы выбираете более одного. Мне пришлось поставить setTimeout, потому что в событии on открытой версии select2, которую вы использовали, на самом деле select еще не нарисован. попробуй сменить версию. Однако это работает.

В качестве альтернативы вы должны заполнить второй выбор динамически, как определено в этой ссылке: Добавить, выбрать или очистить элементы

...