选择Jquery选择而不是添加类

我正在学习
Jquery.我想了解所选的选项.

所以当用户选择一个选项时,我可以做点什么.

我试图运行Jquery,以便当用户选择customAmountSelected时,它应该将一个类’xxx’添加到customAmountinput

$(document).ready(function() {
  if ($("#amountSelected:selected").val() == 'customAmountSelected') {
    $('.customAmountinput').addClass('xxx');
  }
});
.displaynone {
  display: none;
}
<div>
  <div class="form-group">
    <label>Budget (&pound;)</label>
    <select class="form-control" id="amountSelected">
      <option selected="selected">No budget</option>
      <option value="5">£5</option>
      <option value="30">£10</option>
      <option value="20">£20</option>
      <option value="50">£50</option>
      <option value="100">£100</option>
      <option value="customAmountSelected">Custom</option>
    </select>
    <p class="small"><em>Need some text here to explain why they can edit budget </em>
    </p>
  </div>
  <!-- appear when user selected custom budget -->
  <div class="form-group displaynone customAmountinput">
    <label>Enter ammount</label>
    <input class="form-control" placeholder="&pound;">
  </div>
  <div class="form-group">
    <div class="checkbox">
      <label>
        <input type="checkbox" value checked>Post to wall?
      </label>
    </div>
  </div>
</div>

最佳答案 您正在处理价值,因此您无需验证“已选择”状态.

您必须侦听事件“change”,并且它必须位于$(document).ready()内,这种事件在窗口/ DOM加载中绑定.

尝试这样的事情:

$(document).ready(function() {
  $("#amountSelected").change(function(){	
     if($(this).val() == 'customAmountSelected'){
       $('.customAmountinput').addClass('xxx');
     }
  });
});
点赞