如何填充第二个< select>根据第一个< select>选项 [英] How to populate second <select> according to first <select> option

查看:62
本文介绍了如何填充第二个< 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="https://ajax.googleapis.com/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;选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆