繁体   English   中英

如何使用jquery和json数组填充另一个选择中的一个选择

[英]How do I populate one select from a choice in another select using jquery and a json array

这是我的选择和一个json数组,可用于根据选择填充第二个div。

我想先擦除第二个选择选项,然后填充这些选项并将所选值设置为第一项

<select name="select1" id="select1" class="form-control">
    <option value="2">Theme 1</option>
    <option value="1">Theme 2</option>
    <option value="0">unnamed theme</option>
</select>

<select name="select2" id="select2" class="form-control">
    <option value="49">Products</option>
</select>

json数组(使用PHP从数据库值创建,以将其回显)

{"2":{"49":"Products"},"1":{"48":"Product 48","50":"Opportunity","51":"Enroll"},"0":{"52":"Discover product 52","53":"Moringa Support","54":"Product 54","55":"product 55"}}

以下是我将如何执行此操作。

本质上它是这样的:

  • 在您的第一选择上添加类select-master
  • 添加一个数据属性select-info其值是保存所需JSON的变量的名称
  • 添加数据属性select-slave其值是选择器,以第二个选择框为目标
  • 将事件处理程序附加到带有select-master类的任何select上
  • select-master更改时,使用选定的值从JSON获取选项,获取第二个选择,并使用options进行填充

请注意 ,我已经更改了JSON的结构。 我这样做是为了使结构具有意义。

 $('.select-master').change(function(){ var $this = $(this); var val = $this.val(); var possibleSelections =window[$this.data('select-info')]; // get the JSON for this box, you could store the JSON in the data attribute itself but this method makes it easier to use the same JSON for multiple boxes easily if needed var $slave = $($this.data('select-slave')).html(''); // get the selector for the other select box, find the box, and clear it's contents all in one go var selection = possibleSelections[val]; if(selection){ $.each(selection.options,function(i,option){ var selected = i == 0 ? 'selected' : ''; $slave.append('<option selected="'+selected+'" value="'+option.value+'">'+option.text+'</option>'); }); } }); var selections = { "0": { options: [{ value: 52, text: "Discover product 52" }, { value: 53, text: "Moringa Support" }, { value: 54, text: "Product 54" }, { value: 55, text: "product 55" }] }, "1": { options: [{ value: 48, text: "Product 48" }, { value: 50, text: "Opportunity" }, { value: 51, text: "Enroll" }] }, "2": { options: [{ value: 49, text: "Products" }] } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="select1" id="select1" class="form-control select-master" data-select-slave="#select2" data-select-info="selections"> <option value="2">Theme 1</option> <option value="1">Theme 2</option> <option value="0">unnamed theme</option> </select> <select name="select2" id="select2" class="form-control"> <option value="49">Products</option> </select> 

暂无
暂无

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

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