在 Bootstrap 选择器上使用 jQuery 取消选择选项

问题描述 投票:0回答:5

我正在使用 Bootstrap 来处理一些 UI 元素:SelectPicker,它允许用户选择多个选项并将其呈现在段落标签中的屏幕上。他们还应该能够删除选定的选项。

这是我的代码,用于将所选选项渲染到屏幕上,以便每个选项旁边都会显示一个“X”,单击它时,所选项目将从屏幕上删除:

//Render selected item to the screen

$('#dataCombo').change(function(){
$('#dataOutput').html('');
var values = $('#dataCombo').val();
for(var i = 0; i < values.length; i += 1) {
$('#dataOutput').append("<p class='removeable'>" + values[i] + " x </p>")
}});

//When the 'X' is clicked, remove that item

$("#dataOutput").on('click','.removeable',function(){
$(this).remove(); //this removes the item from the screen
//Next i need to unselect it from dataCombo selectpicker
var foo = $(this);
$('#dataCombo').find('[value=foo]').remove();
console.log(foo);
$('dataCombo').selectpicker('refresh');
});   

所以问题是“删除”代码的后半部分,虽然该项目确实从输出显示中删除,但它仍然在选择选择器中被选中,因此当选择另一个项目时 -“已删除”项目将被重新选择呈现。我有什么想法可以做到这一点吗?

HTML 非常简单:

<h6>ComboBox</h6>
<select id="dataCombo"  class="selectpicker" multiple>
</select>
javascript jquery html twitter-bootstrap
5个回答
9
投票

这是使用

deselectAll()
方法的工作示例。

Bootplyhttp://www.bootply.com/124259

JS

//Render selected item to the screen

$('#dataCombo').change(function(){
$('#dataOutput').html('');
var values = $('#dataCombo').val();
for(var i = 0; i < values.length; i += 1) {
$('#dataOutput').append("<p class='removeable'><span class='reel'>" + values[i] + "</span> x </p>")
}});

//When the 'X' is clicked, remove that item

$("#dataOutput").on('click','.removeable',function(){
$(this).remove(); //this removes the item from the screen
//Next i need to unselect it from dataCombo selectpicker
var foo = $(this);
$('#dataCombo').find('[value='+foo.find('.reel').html()+']').remove();
 //  $('#dataCombo').val(  );
$values = $('#dataCombo').val();
$('#dataCombo').selectpicker('deselectAll');
$('#dataCombo').selectpicker('val', $values );
$('#dataCombo').selectpicker('refresh');
});

  $("#dataCombo").selectpicker({
    multiple:true
  });

更新

改变

$('#dataCombo').find('[value='+foo.find('.reel').html()+']').remove();

$('#dataCombo').find('[value='+foo.find('.reel').html()+']').prop('selected', false);

8
投票

我从以下代码中得到了解决方案。尝试一下

$("#listID").val('').trigger('change');

6
投票

因为下面的代码适用于普通选择框

$('#myselect option').prop("selected", false);

我尝试了下面的代码以及 UWU_SANDUN 的答案,它也很好用

$('#myselect option').prop("selected", false).trigger('change');

1
投票

无需使用JQuery。假设用户正在使用 bootstrap-select ... https://developer.snapappointments.com/bootstrap-select/

将选择变成“多个”选择列表并将“data-max-options”设置为1。例如:

<select class="selectpicker" title="Select..." multiple="multiple" data-max-options="1">
  <option>Hello Title 1</option>
  <option>Hello Title 2</option>
  <option>Hello Title 3</option>
</select>

0
投票

对我来说,

selectpicker('deselectAll' and 'refresh')
不起作用:/

但是此命令允许您取消选择当前选定的选项:

$(dataCombo).selectpicker('val','');

使用 Boostrap 5.3 和 bootstrap-select > 1.14.0 进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.