【问题标题】:I need to display the text "Select the one" in the combo box by default我需要默认在组合框中显示文本“选择一个”
【发布时间】:2013-01-13 02:28:23
【问题描述】:

我正在创建一个从 JSON 加载选项的组合框。它按预期加载菜单。但默认情况下,我需要在组合框中显示文本“选择一个”。我试过但找不到解决方案..你能给我建议吗,我怎样才能实现它?

window.onload = function() {
    var obj = JSON.parse(str);    

    for (var i=0; i < obj.MenuParentTabs.length; i++)    {
        var option = document.createElement("option");    
        option.innerHTML = obj.MenuParentTabs[i].parentTabName;
        document.form1.fruits.appendChild(option);
    }
}

【问题讨论】:

  • 向我们展示您的相关 HTML 或在 jsfiddle 上构建一个简单示例可能会有所帮助。
  • 使用&lt;select id="fruits"&gt;&lt;option value=""&gt;Select the one&lt;/option&gt;&lt;/select&gt; 初始化选择一个空的&lt;select&gt; 无论如何都不是有效的HTML。
  • Really?? Yousearched 寻求解决方案?

标签: javascript html drop-down-menu selection


【解决方案1】:

您需要使用您想要的文本创建option for 循环之前:

var option = document.createElement("option");
option.innerHTML = "Select the one";
document.form1.fruits.appendChild(option);

如果option 不是select 的第一个孩子(即,由于某种原因,您没有将它放在for 循环之前),那么还要设置selected 属性:

option.setAttribute("selected", "selected");

帮助 OP 的完整代码:

window.onload = function() {
    var obj = JSON.parse(str);    

    var option = document.createElement("option");
    option.innerHTML = "Select the one";
    option.setAttribute("selected", "selected");
    document.form1.fruits.appendChild(option);

    for (var i = 0; i < obj.MenuParentTabs.length; i++) {
        option = document.createElement("option");
        option.innerHTML = obj.MenuParentTabs[i].parentTabName;
        document.form1.fruits.appendChild(option);
    }
}

【讨论】:

  • 您还应该将 selected 添加到此选项中,也许还应该添加“禁用”?或者在显示菜单时使用 Javascript 将其删除。
  • @Asitaka,如果它是第一个选项,则默认情况下它已经被选中......关于disabled的建议,OP当然可以做到。由于问题中没有说,我将在答案中保持开放状态。
  • 这是真的,但是 OP 可能会添加选项或做一些改变顺序的事情,指定“selected”会强制选择它,无论顺序如何。
  • 好的,我解释得更好一些,以防他们没有将代码放在for 循环之前。
  • @ErickPetru :我按照你上面提到的做了,但是我只得到了组合框中循环中的最后一项。
【解决方案2】:

尝试在你的 for 循环之前添加这样的内容:

var option = document.createElement("option");    
option.innerHTML = "Select One";
document.form1.fruits.appendChild(option);

对于这些恶作剧,我也强烈推荐 jQuery。

【讨论】:

  • @hhamitlton :我按照你上面提到的那样做了,但是我只得到了组合框中循环中的最后一项。
【解决方案3】:

这里有一个非常相似的问题和答案:

HTML select: how to set default text which won't be shown in drop-down list?

basically do this:
var option = document.createElement("option");
option.innerHTML = "Select the one";
option.setAttribute("selected", "selected");
option.setAttribute("disabled", "disabled");
document.form1.fruits.appendChild(option);

我想如果你真的想彻底,你可以添加一些东西来在菜单出现时隐藏这个选项。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多