如何从javascript中的下拉列表中删除选项?

时间:2010-12-31 18:09:55

标签: javascript select combobox

是否有任何示例允许我使用JavaScript从下拉列表中删除选项?

以下是代码:

<select autocomplete="off" id="sSec1" tabindex="0" name="sSec1" class="isSelected styled security selectOriginal">
      <option id="" value="">Select</option>
      <option id="o1" value="What is the name of your first pet?">What is the name of your first pet?</option>
      <option id="o2" value="What is your favorite food?">What is your favorite food?</option>
      <option id="o3" value="What is your favorite holiday?">What is your favorite holiday?</option>
      <option id="o4" value="What is your favorite movie?">What is your favorite movie?</option>
      <option id="o5" value="What is your favorite sport?">What is your favorite sport?</option>
      <option id="o6" value="In what city were you born?">In what city were you born?</option>
      <option id="o7" value="What is your mother's maiden name?">What is your mother's maiden name?</option>
    </select>

这是清单2:

<select autocomplete="off" id="sSec2" tabindex="0" name="sSec2" class="isSelected security styled">    
      <option id="" value="">Select Second Question</option>
      <option id="o1s2" value="What is the name of your first pet?">What is the name of your first pet?</option>
      <option id="o2s2" value="What is your favorite food?">What is your favorite food?</option>
      <option id="o3s2" value="What is your favorite holiday?">What is your favorite holiday?</option>
      <option id="o4s2" value="What is your favorite movie?">What is your favorite movie?</option>
      <option id="o5s2" value="What is your favorite sport?">What is your favorite sport?</option>
      <option id="o6s2" value="In what city were you born?">In what city were you born?</option>
      <option id="o7s2" value="What is your mother's maiden name?">What is your mother's maiden name?</option>
    </select> 

现在我想要发生的是当安全问题编号1选择了任何选项时。对于安全问题2,该选项不应该存在。

1 个答案:

答案 0 :(得分:6)

您可以通过将其设置为null来删除选项。

document.getElementById("sSec1").options[0] = null;

编辑:

以下是一个工作示例:http://jsfiddle.net/c5wFn/

document.getElementById("sSec1").addEventListener("change", 
    function(select)
    {
        if (this.value != "")
        {
            var select2 = document.getElementById("sSec2");
            for (var i = 0; i < select2.options.length; i++)
            {
                if (this.value == select2.options[i].value)
                {
                    select2.options[i] = null;
                    break;
                }
            }
        }
    }, false);

您需要做的一件事是,当一个选项被更改时,您可能需要返回第一个列表项并将所有未选择的项添加到列表中,以便您放回原来的问题删除前一个选择。我不应该努力解决所有细节。

也不确定你是否使用jquery,所以我使用普通的旧javascript。但是应该测试事件注册的兼容性,因为这不适用于所有。