Reputation: 107
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 (£)</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="£">
</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
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
Reputation: 15112
While changing the option, the jQuery .change
event gets triggered. Note that, for getting the value, just use this.value
$("#amountSelected").change(function() {
if (this.value == 'customAmountSelected') {
$(".customAmountinput").toggleClass("displaynone xxx");
} else {
$(".customAmountinput").addClass("displaynone");
$('.customAmountinput').removeClass('xxx');
}
});
Upvotes: 0
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