duanchigeng4313 2014-09-15 18:45
浏览 32
已采纳

Javascript根据所选选项隐藏值

I need help with some javascript. The idea is to hide some values from a depending on a parent

here is the 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>

Do you have any idea to make the javascript hide options with the id that doesnt match with the value of the option selected on the first select?

Thanks for helping !

  • 写回答

1条回答 默认 最新

  • dousaoxiancy199896 2014-09-15 19:13
    关注

    You can do it like this:

    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();
        }
    }
    

    You also have to add a data-phase attribute to your ssphases options so that you can link them together, like this:

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

    I used jQuery for $().hide and $().show.

    Here's a fiddle.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False