下拉框值启用Field

时间:2017-04-20 18:05:26

标签: javascript html

我有以下代码来运行我的下拉框和字段我希望在值不等于下拉列表中的值时禁用。

我的代码如下。

document.getElementById('type').addEventListener('change', function() {
  if (this.value == Hijacking) {
    document.getElementById('hijacking').disabled = false;
  } else {
    document.getElementById('hijacking').disabled = true;
  }
});
<div class="width-qrtr">
  <label>Type of event</label>
  <select name="Type" id="select">
          <option value="">Select Type</option> 
          <option value="Fraud">Fraud</option>
          <option value="Theft">Theft</option>
          <option value="Accident">Accident</option>
          <option value="Hijacking">Hijacking</option>
     </select>
</div>
<div class="width-qrtr">
  <label>Police Station</label>
  <input id="textbox" disabled="true" type="text" name="Test" />
</div>

它会禁用该字段。如果我将值更改为数字它可以工作,但我需要将SQL值插入我的数据库

2 个答案:

答案 0 :(得分:1)

document.getElementById仅在您将相应的ID设置为id="..."时才有效。另外要比较字符串值,你必须将它们放在quotes =&gt;中this.value == 'Hijacking'

更正后的代码如下所示:

&#13;
&#13;
document.getElementById('select').addEventListener('change', function() {
  if (this.value == 'Hijacking') {
    document.getElementById('textbox').disabled = false;
  } else {
    document.getElementById('textbox').disabled = true;
  }
});
&#13;
<div class="width-qrtr">
  <label>Type of event</label>
  <select name="Type" id="select">
          <option value="">Select Type</option> 
          <option value="Fraud">Fraud</option>
          <option value="Theft">Theft</option>
          <option value="Accident">Accident</option>
          <option value="Hijacking">Hijacking</option>
     </select>
</div>
<div class="width-qrtr">
  <label>Police Station</label>
  <input id="textbox" disabled="true" type="text" name="Test" />
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您的代码中的错误很少,修复如下:

&#13;
&#13;
document.getElementById('select').addEventListener('change', function() {
  if (this.value == "Hijacking") {
    document.getElementById('textbox').disabled = false;
  } else {
    document.getElementById('textbox').disabled = true;
  }
});
&#13;
<div class="width-qrtr">
  <label>Type of event</label>
  <select name="Type" id="select">
          <option value="">Select Type</option> 
          <option value="Fraud">Fraud</option>
          <option value="Theft">Theft</option>
          <option value="Accident">Accident</option>
          <option value="Hijacking">Hijacking</option>
     </select>
</div>
<div class="width-qrtr">
  <label>Police Station</label>
  <input id="textbox" disabled="true" type="text" name="Test" />
</div>
&#13;
&#13;
&#13;