我正在使用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("

" + values[i] + " x

")

}});

//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非常简单:

ComboBox

解决方法:

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

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("

" + values[i] + " x

")

}});

//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);

标签:jquery,javascript,twitter-bootstrap,html

来源: https://codeday.me/bug/20190717/1491244.html

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐