从其他选择输入中删除所选项目

时间:2012-02-26 18:24:57

标签: javascript jquery html

选择输入项时遇到问题。

我想要实现的是从其他选择框中动态删除已选择的选项,这样我就无法在多个框中选择相同的项目。问题是元素是通过AJAX加载到数组中的,我需要用后面的选项填充选择输入。这使得它变得更加困难。

简而言之 - 如何确保如果我在选择中选择一个项目,它将被删除所有其他项目,但当我选择其他项目时,前一个项目将再次显示,等等...

我也有一个小提琴,这是我得到了多远:http://jsfiddle.net/P3j4L/

1 个答案:

答案 0 :(得分:3)

您可以尝试这样的事情

function updateSelects()
{
  $('.selectContainer .select').each(
    function (i, elem)
    {
        // Get the currently selected value of this select
        var $selected = $(elem).find("option:selected"); 
        // Temp element for keeping options
        var $opts = $("<div>");
        // Loop the elements array
        for (i = 0; i < selectElements.length; i++)
        {
            var value = selectElements[i];
            // Check if the value has been selected in any select element
            if ($selected.val() == value || !$('.select option[value=' + value + ']:selected').length)
            {
                 // if not create an option and append to temp element
                 $opts.append('<option value="' + value + '">' + value + '</option>');
            }
        }
        // replace the html of select with new options
        $(elem).html($opts.html());
        if ($selected.length)
        {
             // set the selected value if there is one
             $(elem).val($selected.val());
        }
        else
        {
             // new select element. So remove its selected option from all other selects
             $('.selectContainer .select').not(this).find('option[value=' + $(elem).val() + ']').remove();
        }
    }
  );
}

在此处查看演示:http://jsfiddle.net/P3j4L/1/

相关问题