2014-03-24 98 views
1

我对一些UI元素使用Bootstrap:SelectPicker,它允许用户选择多个选项并将它呈现到段落标记中的屏幕。他们也应该能够删除选定的选项。在Bootstrap selectpicker上取消选择使用jQuery的选项

这是我的代码,以使所选择的选项在屏幕上,让每一个选项出现有“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> 

回答

1

下面是使用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 
    }); 

UPDATE

变化

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

通过

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

嗨,非常感谢,但不是取消选择该选项,而是将其从bootply示例的选项列表中删除。我如何解决这个问题? – Hagbard

+0

@Hagbard看到我的更新 – pbenard

+0

谢谢,你的代码似乎在bootply上工作正常,但它似乎没有做我的任何事情,我会接受你的答案,并尝试在我的最后调试它。谢谢 – Hagbard

3

我的解决方案从以下code.Try它

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

谢谢你的工作 –

1

由于下面的代码工作正常选择框

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

我尝试下面的代码的答案从UWU_SANDUN也很好用

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