在Select2中选择Option - 禁用/启用不触发的操作

时间:2017-10-31 18:40:36

标签: javascript jquery forms jquery-select2

我有一个选择Select2下拉框和一个默认禁用的空白文本框。

当用户选择一个选项,即“ServiceNow”时,我希望文本框将disabled设置为false。

目前,功能似乎是随机的。四个可用选项中的两个启用该字段,两个禁用它。甚至不是我想要的那个使它成功。我在这里做错了什么?

表单HTML

<div>
  <label for="feature">Feature</label>
  <select class="form-control select2" style="width: 100%;" name="feature" id="feature">
    <option selected="selected" disabled="disabled">-Select-</option>
    <option name="ServiceNow" value="ServiceNow">Service Now</option>
    <option>Epic Upgrade</option>
    <option>Alarais Interop</option>
    <option>Pyxis Upgrade</option>
  </select>
</div>
<div class="col-xs-4">
  <label for="serviceNowID">ServiceNow ID</label>
  <input type="text" class="form-control" name="serviceNowID" id="serviceNowID" disabled="disabled" placeholder="ServiceNow ID (This doesn't work yet.)">
</div>

相关JS

<script> 
//Get the ServiceNow thing to unlock on option select
//Evaluate if option is selected
$('#feature').on("select2:selecting", function(e) { 
   var choice = $(this).find('option').val();

   if ($(this).val() == 'ServiceNow') {
    document.getElementById("serviceNowID").disabled = false;
   } else {
    document.getElementById("serviceNowID").disabled = true;
   }
});
</script>

谢谢!

2 个答案:

答案 0 :(得分:1)

  

当用户 选择 一个选项时,即&#34; ServiceNow&#34;我希望文本框将disabled设置为false。

也许你应该使用&#39; select&#39;事件而不是选择&#39;?

$('#feature').on("select2:select", function(e) { 
...

答案 1 :(得分:1)

以下是一个可以帮助您的示例:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <label for="feature">Feature</label>
  <select class="form-control select2" style="width: 100%;" name="feature" id="feature">
                <option selected="selected" disabled="disabled">-Select-</option>
                <option name="ServiceNow" value="ServiceNow">Service Now</option>
                <option>Epic Upgrade</option>
                <option>Alarais Interop</option>
                <option>Pyxis Upgrade</option>
              </select>
</div>
<div class="col-xs-4">
  <label for="serviceNowID">ServiceNow ID</label>
  <input type="text" class="form-control" name="serviceNowID" id="serviceNowID" disabled="disabled" placeholder="ServiceNow ID (This doesn't work yet.)">
</div>

<script>
  //Get the ServiceNow thing to unlock on option select
  //Evaluate if option is selected
  $('#feature').on("change", function(e) {

    if ($(this).val() == 'ServiceNow') {
      $("#serviceNowID").attr('disabled',false);
    } else {
       $("#serviceNowID").attr('disabled',true);
    }
  });
</script>
&#13;
&#13;
&#13;