试图使所选属性起作用

时间:2019-03-15 08:39:48

标签: jquery

我正在尝试使选中的菜单具有选中的属性。我遇到的问题是,当选择该选项时,它仍会转到第一个可用选项。

这是我的代码

<div class="content_wrapper">
    <div class="row">
        <div class="col-lg-12">
            <form action="{{ route('account.sort-orders') }}">
                <select class="sort_orders" name="sort_orders">
                    <option class="all" value="all" selected>All</option>
                    <option class="three_months" value="three_months">Last 3 months</option>
                    <option class="six_months" value="six_months">Last 6 months</option>
                    <option class="2019" value="2019">2019</option>
                </select>
            </form>
        </div>
    </div>
</div>

<script>
    $(document).ready(function(){
        $('.sort_orders').change(function(){
            $(this).closest("form").submit();
        });

        $("select.sort_orders").change(function(){
            var selectedOpton = $(this).children("option:selected").val();
            console.log("You have selected this option - " + selectedCountry);

            if(selectedOpton == 'three_months'){
                console.log('this is three_months');
                $('.all').removeAttr('selected');
                $('.three_months').attr('selected', true);
            }
        });
    });

</script>

1 个答案:

答案 0 :(得分:0)

当然有更有效的方法可以做到这一点。但是,我认为这是您要实现的目标。

<div class="content_wrapper">
    <div class="row">
        <div class="col-lg-12">
            <form action="{{ route('account.sort-orders') }}">
                <select id="yourSlct" class="sort_orders" name="sort_orders">
                    <option class="all" value="all" selected>All</option>
                    <option id="option2" class="three_months" value="three_months">Last 3 months</option>
                    <option class="six_months" value="six_months">Last 6 months</option>
                    <option class="2019" value="2019">2019</option>
                </select>
            </form>
        </div>
    </div>
</div>

<script>

$(document).ready(function(){

    $('.sort_orders').change(function(){
        $(this).closest("form").submit();
    });

    $("select.sort_orders").change(function(){
        var selectedOpton = $(this).children("option:selected").val();
        $('#text').text(selectedOpton);

        $('#yourSlct').children().removeAttr("selected");

        if(selectedOpton == 'three_months'){
            console.log('this is three_months');
            $("select.sort_orders #option2").attr("selected", "selected");
        }
    });
});

</script>