动态选择每个选择框的多选选择框的setAttribute

时间:2018-12-24 17:46:19

标签: javascript jquery express bootstrap-select

我的表单中有一些多选选择框,为了使它们看起来更好,我使用了引导选择。由于此应用程序的核心是在Express中开发的,因此我无法获取用户选择的值,因为引导程序选择会生成div和用户实际与之交互的列表。为了解决这个问题,我正在尝试编写一些javascript / jquery,以将selected = true添加到所选的每个选项中。我知道了,但是后来意识到,如果我取消选择一个选项,它仍然显示为selected = true。

我尝试使用$(this).find("option:not(:selected)").get(i).setAttribute('selected', false); 但是,这在进行多个选择后会引发错误。

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>

脚本

$(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消失。

1 个答案:

答案 0 :(得分:1)

尝试一下:

$(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);

});
})