Reputation: 280
I am attempting to change the visibility of the second div with the class .form-group
. Using jQuery I am trying to grab the value of the selected option and then based upon that value change the aforementioned visibility.
If the value is 0 then the second div .form-group
should become visible. I am having difficulties with this, I have tried parents()
and closest()
, however, I believe I have been implementing these incorrectly
HTML
<div class="form-group">
<label class="control-label required" for="userQuestions[1]">Do you have any dietary requirements? <span class="required">*</span></label><select class="form-control user-success" id="userQuestions_1" name="userQuestions[1]" required="required">
<option value="">
Please select
</option>
<option value="0">
Yes
</option>
<option value="1">
No
</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="userQuestions[2]">Would you like to stay for after conference drinks?</label><select class="form-control" id="userQuestions_2" name="userQuestions[2]">
<option value="">
Please select
</option>
<option value="0">
Yes
</option>
<option value="1">
No
</option>
</select>
</div>
JQuery
$(document).ready(function(){
$('#useQuestion[1]').change(function(){
if($(this).val() == '0'){
$('.form-group:nth-of-type(2)').addClass('visible');
}
});
});
CSS
.form-group:nth-of-type(2) {
visibility: hidden;
}
.visible {
visibility: visible !important;
}
Upvotes: 1
Views: 407
Reputation: 5869
in your function replace this ('#useQuestion[1]')
to ('#userQuestions_1')
I just modified your code check here
$(document).ready(function(){
$('#userQuestions_1').on('change',function(){
if($(this).val() == '0'){
$('.form-group:nth-of-type(2)').addClass('visible');
}
});
});
.form-group:nth-of-type(2) {
visibility: hidden;
}
.visible {
visibility: visible !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label required" for="userQuestions[1]">Do you have any dietary requirements? <span class="required">*</span></label><select class="form-control user-success" id="userQuestions_1" name="userQuestions[1]" required="required">
<option value="">
Please select
</option>
<option value="0">
Yes
</option>
<option value="1">
No
</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="userQuestions[2]">Would you like to stay for after conference drinks?</label><select class="form-control" id="userQuestions_2" name="userQuestions[2]">
<option value="">
Please select
</option>
<option value="0">
Yes
</option>
<option value="1">
No
</option>
</select>
</div>
Upvotes: 1