如何填充第二个< select>根据第一个< select>选项

编程入门 行业动态 更新时间:2024-10-27 09:40:51
本文介绍了如何填充第二个< select>根据第一个< select>选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个脚本,在其中根据第一个<select>选项填充第二个选择.

I am trying to make a script where I populate a second select according to the first <select> option.

例如,如果我在第一个<select>上选择类别1,则需要在第二个类别中填充子类别1.1,子类别1.2等.

For example, if I select Category 1 on the first <select>, I need the second one to be populated with Subcategory 1.1, Subcategory 1.2, etc.

这是我的代码:

<select id="category"> <option value="">Select Category</option> <option value="1">Category 1</option> <option value="2">Category 2</option> <option value="3">Category 3</option> </select> <select id="subcategory"> <option value=""></option> </select>

我正在尝试用jquery做到这一点.有人可以帮我吗?

I am trying to do this with jquery. Can someone help me with this?

推荐答案

var categories = [ { value: '1', name: 'Category 1', subCategories: [{ value: '1.1', name: 'Sub 1.1' }, { value: '1.2', name: 'Sub 1.2' }] }, { value: '2', name: 'Category 2', subCategories: [{ value: '2.1', name: 'Sub 2.1' }, { value: '2.2', name: 'Sub 2.2' }] } ]; var $categorySelect = $("#category"); var $subCategorySelect = $("#subcategory"); // populate categories with options categories.forEach(function(category) { var $option = $('<option/>').attr('value', category.value).html(category.name); $categorySelect.append($option); }); $categorySelect.on('change', function() { // clean subcategory select from older options $subCategorySelect.empty(); // find selected category var selectedCategoryValue = $categorySelect.val(); var category = categories.find(function(category) { return category.value == selectedCategoryValue; }); // if category found - populate subcategory select if (category) { category.subCategories.forEach(function(subcategory) { // you can extract this line into separate function var $option = $('<option/>').attr('value', subcategory.value).html(subcategory.name); $subCategorySelect.append($option); }); } })

<script src="ajax.googleapis/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="category"> <option value="">Select Category</option> </select> <select id="subcategory"> <option value=""></option> </select>

更多推荐

如何填充第二个&lt; select&gt;根据第一个&lt; select&gt;选项

本文发布于:2023-10-31 01:58:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1544651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   第二个   选项   amp   select

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!