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

Hag*_*ard 6 html javascript jquery twitter-bootstrap

我正在将 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');
});   
Run Code Online (Sandbox Code Playgroud)

所以问题是“删除”代码的后半部分,虽然该项目确实从输出显示中删除了,但它仍然在选择选择器中被选中,所以当另一个项目被选中时——“删除”项目被重新渲染. 任何想法我怎么能做到这一点?

HTML非常简单:

<h6>ComboBox</h6>
<select id="dataCombo"  class="selectpicker" multiple>
</select>
Run Code Online (Sandbox Code Playgroud)

Pim*_*Web 7

这是一个使用deselectAll()方法的工作示例。

引导http : //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
  });
Run Code Online (Sandbox Code Playgroud)

更新

改变

$('#dataCombo').find('[value='+foo.find('.reel').html()+']').remove();
Run Code Online (Sandbox Code Playgroud)

经过

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


UWU*_*DUN 6

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

$("#listID").val('').trigger('change');
Run Code Online (Sandbox Code Playgroud)


小智 5

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

$('#myselect option').prop("selected", false);
Run Code Online (Sandbox Code Playgroud)

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

$('#myselect option').prop("selected", false).trigger('change');
Run Code Online (Sandbox Code Playgroud)