简体   繁体   English

如何存储数据并基于另一个选择值分配选择选项?

[英]How to store data and assign select options based on another select value?

I have first select with multiple options and another select: 我首先选择了多个选项,然后再选择一个:

<select class="form-control" id="select1">
  <option value="">Choose</option>
    <option value="1">select1_option1</option>
    <option value="2">select1_option2</option>
    ...
<select class="form-control" id="select2">
  <option value="">Choose</option>
  ...

Available options in select2 are dependent on chosen value in select1 . select2中的可用选项取决于select1所选值。

The data could be stored in the following format (or any other, but should be minimized): 数据可以以下格式存储(或其他任何格式,但应将其最小化):

var select2data = {1:{11:"select2_option1",12:"select2_option2",13:"select2_option3",14:"select2_option4"},
                   2:{21:"select2_option1",22:"select2_option2"}};

So, if value 1 is chosen in the first select, then select2 should look like below: 因此,如果在第一个选择中选择了值1 ,则select2应该如下所示:

<select class="form-control" id="select2">
  <option value="">Choose</option>
  <option value="11">select2_option1</option>
  <option value="12">select2_option2</option>
  ...

I know how to assign new values to the select2 , but I don't understand how to read select2data values - see jsfiddle . 我知道如何为select2分配新值,但我不了解如何读取select2data值-请参阅jsfiddle

You have to do it this way: 您必须这样做:

 $('#select2')
        .find('option')
        .remove()
        .end()

    $.each(select2data[value], function (index, item) {
        console.log(item)
        $('#select2').append('<option value="' + index + '">' + item + '</option>')
    })

FIDDLE DEMO: 演示区:

http://jsfiddle.net/4ujs6jf9/3/ http://jsfiddle.net/4ujs6jf9/3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM