我正在为某些 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/