问题描述
我有一个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);
解决方法
测试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>';
}
,
假设您有一个ID为 opt1 的选项,如
<option value="your_value" id="opt1">option text</option>
那么你可以做
document.getElementById('opt1').setAttribute('selected','selected')
P.S。仅当您使用本地选择时,此方法才有效。另一种选择是使用伪选择