我正在尝试使用类.form-group
更改第二个div的可见性。使用jQuery我试图获取所选选项的值,然后根据该值更改上述可见性。
如果值为0,则第二个div .form-group
应该可见。我遇到了这方面的困难,我尝试了parents()
和closest()
,但是,我相信我一直在实施这些错误
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;
}
答案 0 :(得分:1)
将此('#useQuestion[1]')
替换为('#userQuestions_1')
我刚修改了你的代码检查
$(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>