根据值筛选 <SELECT> 选项

我有 2 个输入选择


国家和汽车


这是结构:[https://jsfiddle.net/CornerStone20/r1eanhwv/6/][1]


JSFIDDLE: [1]:https ://jsfiddle.net/CornerStone20/r1eanhwv/6/


当我选择国家时,如何只显示所选国家的汽车?


我试过了:


$(function() {

    $('#Country_Select').on('change', function() {

        var val = this.value;

        $('#Cars_Select option').hide().filter(function() {

            return this.value.indexOf( val + '_' ) === 0;

        })

        .show();

    })

    .change();

});


侃侃尔雅
浏览 78回答 2
2回答

qq_花开花谢_0

您可以使用each循环遍历选项并检查 select-box 的值car是否与 select-box 相同,country具体取决于 thisshow()或hide()options 。演示代码:$(function() {&nbsp; $('#Country_Select').on('change', function() {&nbsp; &nbsp; var val = this.value;&nbsp; &nbsp; $('#Cars_Select option').each(function() {&nbsp; &nbsp; &nbsp; //checking value of opton in cars selct is same&nbsp; &nbsp; &nbsp; if ($(this).val() == val) {&nbsp; &nbsp; &nbsp; &nbsp; $(this).show(); //show it&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; $(this).hide(); //hide other&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; })});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>// Country select<select id="Country_Select" class="form-control">&nbsp; <option selected="true" disabled="false">Choose Country</option>&nbsp; <option value="0001">France</option>&nbsp; <option value="8ebd9ec1-b121-44e9-a530-42f227359913">Germany</option>&nbsp; <option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">New Zealand</option></select>// Cars<select id="Cars_Select" class="form-control">&nbsp; <option selected="true" disabled="false">Choose Cars</option>&nbsp; <option value="0001">Renauld</option>&nbsp; <option value="0001">Mini</option>&nbsp; <option value="0001">Paris</option>&nbsp; <option value="8ebd9ec1-b121-44e9-a530-42f227359913">BMW</option>&nbsp; <option value="8ebd9ec1-b121-44e9-a530-42f227359913">Audi</option>&nbsp; <option value="8ebd9ec1-b121-44e9-a530-42f227359913">Mercedes</option>&nbsp; <option value="8ebd9ec1-b121-44e9-a530-42f227359913">Benz</option>&nbsp; <option value="4dda2683-83c6-48c8-af9b-0a96991b7c8b">Kiwi Auto</option></select>

SMILET

尽管问题已经得到解答,但我在这里写了一个更好的方法:$('#Country_Select').on('change', function(e) {&nbsp; let cars = $('#Cars_Select').children();&nbsp; cars.hide();&nbsp; let country = $(this).val();&nbsp; cars.filter('[value=' + country + ']').add(cars.eq(0)).show();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript