Javascript根据所选选项隐藏值

时间:2014-09-15 18:45:22

标签: javascript php html twig

我需要一些javascript的帮助。我们的想法是隐藏一些取决于父母的值

这是html

<div class="form-group" style="margin-top: 20px;">
    <label for="inputPassword3" class="col-sm-2 control-label">Phase</label>
    <div class="col-sm-10">
        <select class="form-control" name="phase" id="phase">
            {%if phases is defined%}
                {%for phase in phases%}
                    <option  value="{{phase.id}}">{{phase.nom}}</option>
                {%endfor%}
            {%endif%}
        </select>
    </div>
</div>
<div class="form-group" >
    <label for="inputPassword3" class="col-sm-2 control-label">Sous phase</label>
    <div class="col-sm-10">
        <select class="form-control" name="ssphase" id="ssphase">
            {%if ssphases is defined%}
                {%for ssphase in ssphases%}
                    <option  value="{{ssphase.id}}" id="{{ssphase.phaseid}}">{{ssphase.nom}}</option>
                {%endfor%}
            {%endif%}
        </select>
    </div>
</div>

您是否有任何想法使javascript隐藏选项的ID与第一个选择中所选选项的值不匹配?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你可以这样做:

phase.onchange = function () {
    show_sphases (this.value);
}

function show_sphases (phase) {
    var subphases = document.querySelectorAll("[data-phase='" + phase + "']");
    var allSubphases = document.querySelectorAll("#ssphase option");

    for (var i = 0; i <= allSubphases.length; i++ ){
        var item = allSubphases.item(i);
        $(item).hide();
    }

    for (var i = 0; i <= subphases.length; i++ ){
        var item = subphases.item(i);
        $(item).show();
    }
}

您还必须在ssphases选项中添加数据阶段属性,以便将它们链接在一起,如下所示:

<option  value="11" id="11" data-phase="1">Subphase #1-1</option>

我将jQuery用于$().hide$().show

这里是fiddle