我正在尝试使用类.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;
}

最佳答案

在您的函数中将此('#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>

关于javascript - 根据子元素的值更改父元素的CSS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44889260/

10-11 11:57