【问题标题】:How to add "selected" attribute dynamically to select option in javascript?如何在javascript中动态添加“selected”属性以选择选项?
【发布时间】:2020-08-23 23:16:46
【问题描述】:

我有一个 javascript 自动表单创建公式。我正在为选择列表中选项的“选定”属性而苦苦挣扎。 我想选择与 const c 匹配的选项(在这种情况下,我想选择“Formation”选项)。

我怎样才能做到这一点? 任何想法 ?非常感谢法国!

const c = "Formation";                

const training_level = document.createElement('select');
training_level.setAttribute('value', c)
training_level.setAttribute('id', 'rec_mode')
training_level.required = true

var j = new Array("-- Type de diplôme --","Formation","Brevet","Bac","Bac +1"),    
var options = '';

for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i]+ '">' + j[i] + '</option>';
}

training_level.appendChild(options);

【问题讨论】:

    标签: javascript options


    【解决方案1】:

    测试c 的值是否与j[i] 的值匹配。使用该条件的值填写selected 属性:

    for (var i = 0; i < j.length; i++) {
        var selected = (c == j[i]) ? "selected" : "";
        options += '<option value="' + j[i]+ '" selected="' + selected + '">' + j[i] + '</option>';
    }
    

    【讨论】:

      【解决方案2】:

      假设您有一个 ID 为 opt1 的选项,例如

      <option value="your_value" id="opt1">option text</option>
      

      那你就可以了

      document.getElementById('opt1').setAttribute('selected', 'selected')
      

      附:这仅在您使用本机选择时才有效。另一种选择是使用假选择

      【讨论】:

        猜你喜欢
        • 2013-12-12
        • 2015-06-15
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 1970-01-01
        • 2015-06-08
        • 2021-04-19
        • 1970-01-01
        相关资源
        最近更新 更多