Jquery selection selected than adding class

I am learning jQuery. I am trying to understand the choices. Therefore, when the user selects a parameter, I can do something.

I am trying to run jquery so that the user, by selecting userAmountSelected, should add the class 'xxx' to 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>
Run codeHide result
+4
source share
3 answers

You are processing a value, so you do not need to check the “selected” state.

You should listen to the "change" event, and it should be inside $ (document) .ready (), this kind of event is tied to loading the window / DOM.

Try something like this:

$(document).ready(function() {
  $("#amountSelected").change(function(){	
     if($(this).val() == 'customAmountSelected'){
       $('.customAmountinput').addClass('xxx');
     }
  });
});
Run codeHide result
+1
source

if . , if . change :

$("amountSelected").change(function(){
        if($("#amountSelected:selected").val() == 'customAmountSelected' ) {
            $('.customAmountinput').addClass('xxx');
        }
    });
0

When the option is changed, the jQuery event is fired .change. Note that to get the value just usethis.value

JSFIDDLE DEMO

$("#amountSelected").change(function() {
  if (this.value == 'customAmountSelected') {
    $(".customAmountinput").toggleClass("displaynone xxx");
  } else {
    $(".customAmountinput").addClass("displaynone");
    $('.customAmountinput').removeClass('xxx');
  }
});
0
source

All Articles