ChrisGuru
ChrisGuru

Reputation: 107

Jquery select is selected than add class

I am learning Jquery. I am trying to to understand the selected options. So when user select a option I can do something.

I trying to run Jquery so that when the user selects customAmountSelected that it should add a 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>

Upvotes: 4

Views: 69

Answers (3)

RPichioli
RPichioli

Reputation: 3345

You are handling value, so you don't need to validate the "selected" state.

You must listen to the event "change", and it must be inside the $(document).ready(), that kind of events are binded in the window/DOM load.

Try something like this:

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

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

While changing the option, the jQuery .change event gets triggered. Note that, for getting the value, just use this.value

JSFIDDLE DEMO

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

Upvotes: 0

Velimir Tchatchevsky
Velimir Tchatchevsky

Reputation: 2825

You are using the if statement on the wrong place. This way the if is evaluated once on document load and that's it. You'll need to bind that to the change event of the input like so:

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

Upvotes: 0

Related Questions