Javascript向选择框添加值

时间:2019-06-28 04:33:19

标签: javascript html drop-down-menu

在我的项目中,我有一个类似这样的HTML:

<div class="form-group">
    <label>Coverage</label>
    <select id="t_cov_e" class="form-control">
       <option>API</option>
       <option>Architecture</option>
       <option>Database</option>
       <option>OS</option>
       <option>Web</option>
       <option>Other</option>
    </select>
</div>
<div class="form-group">
   <label>Credits (Price)</label>
   <select id="t_price_e" class="form-control">
       <option>1</option>
       <option>3</option>
       <option>6</option>
       <option>9</option>
       <option>12</option>
    </select>
</div>

好吧,当我选择上面的表格时,我想用单击的行值填充代码中选择框的显示值,为此我创建了一个js

document.getElementById("t_cov_e").value = this.cells[7].value;
document.getElementById("t_price_e").value = this.cells[5].value;

但是当我尝试我的代码时,选择标记t_price_e正确填充,但是t_cov_e什么也不做。我检查了传递的值,就算可以,即使我用以下方式更改行:

document.getElementById("t_cov_e").value = "Test";

什么都没有改变;当我查看HTML时,选择标记t_cov_e不显示任何默认值。

这怎么可能? 如何使用javascript为我的选择标签设置默认值?

谢谢。

1 个答案:

答案 0 :(得分:0)

如果您要设置值,则可以使用


window.onloaded=load();

function load(){
var leaveCode = document.querySelector('#t_cov_e');
leaveCode[3].selected = true;
}

工作演示:https://jsfiddle.net/athulmathew/4Lwr06tj/22/

但是为什么在只有5个单元格的情况下尝试设置this.cells[7].value