动态设置多项选择的属性 select box with each choice

Dynamically setAttribute of multiple choice select box with each choice

我的表单中有几个多项选择 select 框,为了使它们看起来漂亮,我使用了 bootstrap select。由于此应用程序的核心是在 Express 中开发的,因此我无法获取用户 select 的值,因为 bootstrap select 生成了 div 和用户列表实际上是在互动。为了解决这个问题,我正在尝试编写一些 javascript/jquery 以将 selected=true 添加到 selected 的每个选项。我想通了,但后来意识到,如果我要 deselect 一个选项,它仍然显示为 selected=true。

我试过使用 $(this).find("option:not(:selected)").get(i).setAttribute('selected', false); 但是,这会在生成多个 select 离子后引发错误。

HTML

 <label for="performThese">I will perform</label>
 <select class="selectpicker show-tick form-control" multiple id="performThese" name="performThese" data-style="btn-secondary" title="Choose your option..">
   <option value="residential_BPO">Residential BPOs</option>
   <option value="commercial_valuation">Commercial Property Valuations</option>
   <option value="condition_report">Property Detail & Condition Reports</option>
  </select>

Javascript

$(function() {
 // Style only selects with the selectpicker class
$('.selectpicker').selectpicker();
 // Get the target multiple select box for testing
let selectTarget = document.getElementsByName('performThese');
 // Wait for a change
$(selectTarget).on('change', function(e){
 // How many options selected?
let selectTargetLength = $(this).find("option:selected").length;
 // Make a blank array
let selectValue = [];
let i = 0;
while (i < selectTargetLength) {
 // Grab value of each choosen option in case needed for evaluation
  selectValue[i] = $(this).find("option:selected").get(i).value;
// Make options choose show as selected
  $(this).find("option:selected").get(i).setAttribute('selected', true);
  i++
}
});
})

我希望 selected=true 在我删除selected 条目后消失。

试试这个:

$(function() {
 // Style only selects with the selectpicker class
$('.selectpicker').selectpicker();
 // Get the target multiple select box for testing
let selectTarget = document.getElementsByName('performThese');
 // Wait for a change
$(selectTarget).on('change', function(e){

    //firstly clean all options:
    $(this).find("option").attr("selected", false);

    //selected options are still available with find("option:selected")

    //marks all selected options:
    $(this).find("option:selected").attr("selected",true);

});
})