如果选择,如何更改<option>的输出值?

时间:2018-03-17 10:42:08

标签: javascript if-statement input

如何为下拉列表中的一个元素赋值,将另一个元素赋予不同的值?

我正在尝试在选择时将不同的值输出到输入字段中 以下只是一个视觉,所以你可以理解这个问题。

<label>Dropdown-List</label>
<select class="form-control" onchange="handicap();">
<option id="c1">Example (5)</option>
<option id="c2">Example (10)</option>

<input type="text" class="form-control" id="cap">

function handicap() {

  var cap1 = document.getElementById('c1');
  var cap2 = document.getElementById('c2');

  if (cap1) {
     document.getElementById('cap').value = 5;
  }

  else {
     document.getElementById('cap').value = 10;
  }
}

1 个答案:

答案 0 :(得分:1)

您的情况应该是cap1.selected而不是cap1。如果if(cap1)不是cap1null,那么您undefined目前的情况就会变为现实,因此在每种情况下cap1都定义为input所以您总是如此满足条件且5设置为cap1.selected的值,但现在当您执行cap1时,它实际检查是否选择了function handicap() { var cap1 = document.getElementById('c1'); var cap2 = document.getElementById('c2'); if (cap1.selected) { document.getElementById('cap').value = 5; } else { document.getElementById('cap').value = 10; } }选项。

&#13;
&#13;
<label>Dropdown-List</label>
<select class="form-control" onchange="handicap();">
<option id="c1">Example (5)</option>
<option id="c2">Example (10)</option>

<input type="text" class="form-control" id="cap">
&#13;
 filter(typ: string) {
console.log("Filter");
this.nagelplattenFiltered == null;
this.nagelplattenFiltered = this.nagelplatten.filter((nagel: Nagelplatten) => nagel.Bezeichnung1 === typ);
this.nagelplatten = this.nagelplattenFiltered;
console.log(JSON.stringify(this.nagelplattenFiltered));
console.log("new: " + JSON.stringify(this.nagelplattenFiltered));
&#13;
&#13;
&#13;