不要在下拉列表中显示所选项目

时间:2015-01-20 10:33:06

标签: javascript jquery html jquery-select2

我有select2下拉列表,其中包含一些值(让我们说颜色),我想从下拉列表中删除当前所选项目。例如,如果所有选项都是

white, green, red, blue

当前所选项目为white,如果用户点击下拉列表,则他只会看到其他3种颜色(green, red and blue)。

现在,我可以使用jquery轻松删除当前选定的项目,并在更改时将其恢复,但这确实不干净。

是否有任何内置方法可以做到这一点,或者至少有一种方法更清洁"?

4 个答案:

答案 0 :(得分:1)

删除选项:

$("#selectBox option[value='White']").remove();

添加选项:

$("#selectBox").append('<option value="greed">Green</option>');

答案 1 :(得分:0)

使用.hide()隐藏它或使用display: none;的自定义类并将其添加到选项中。

$(".selector option[value=white]").hide()

对于跨浏览器支持,请禁用它而不是隐藏它。

$(".selector option[value=white]").prop("disabled", true)

答案 2 :(得分:0)

您可以使用:从jQuery库中选择。

( "select" )
   .change(function() {
   var str = "";
   $( "select option:selected" ).each(function() {
   (select option:selected).text() = " ";
});

答案 3 :(得分:0)

您可以使用templateResult选项自定义您在下拉列表中看到的选项。如果您不想显示某些选项,也可以使用此选项。

您传递javascript函数作为templateResult选项的值。例如:

$('#color').select2({
    templateResult: formatColorOption
});

在select元素上调用.select2()之前,首先需要定义formatColorOption() javascript方法。例如:

function formatColorOption (color) {
    if (!color.id) { return color.text; }
    // this next line prevents the currently selected option from showing up in the dropdown list
    if ($('#color').find(':selected').val() == color.element.value) { return null; }
    // otherwise display the name of the color
    return color.text;
};

要查看将TemplateResult与其他一些选项相结合的精美示例,请查看JSFiddle。 https://jsfiddle.net/vatdoro/4xu6vcc5/