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

标签 javascript jquery html twitter-bootstrap

我正在为某些 UI 元素使用 Bootstrap: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>

最佳答案

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

Bootstrap :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
  });

更新:

改变

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

通过

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

关于javascript - 在 Bootstrap 选择器上使用 jQuery 取消选择一个选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606542/

相关文章:

javascript - 在 React 中单击按钮时使文本淡入/淡出

javascript - 如果元素可见,则自动增加步数

javascript - 在页面中加载远程 JavaScript 文件

javascript - 在单独的切换更改上切换多个复选框

javascript - 在纯 JavaScript 中加载多个 JSON 文件

javascript - javascript/jquery 的标准调试方式

html - 变换 css 使菜单消失

html - 带有搜索栏的中心 Logo 向右 Bootstrap

javascript - 未捕获的类型错误 : not a function when calling method from data in Vue

javascript - 如何捕获 iframe 中下载的文件?