如何创建n级(多级,级联)依赖下拉列表(选择,选项)?

时间:2014-08-14 06:29:14

标签: php jquery html mysql json

目的:使用工具jquery(javascript),php,mysql找到创建级联下拉列表的最简单,更灵活的方法;

如果您有其他更简单/更灵活的选择,请分享。

1 个答案:

答案 0 :(得分:0)

<强> HTML

<select class="step1 step" name="step1"></select>
<select class="step2 step" name="step2"></select>
<select class="step3 step" name="step3"></select>
<select class="step4 step" name="step4"></select>
<select class="step5 step" name="step5"></select>

出于提供信息的目的,通常选择最后一个下拉列表:

<textarea id="info" disabled=""></textarea>

<强> JQUERY

$.get(url, function(data){
    var options = function(data, level, selected) {
        $.each(data, function(i, item) {
            var pid = $('.step'+(level-1)).val();

            if(pid == item.pid || item.pid == 0) {
                if(!$('.step').find('option[value='+item.id+']').length) {
                    $('.step'+level).append($('<option>', {
                        value: item.id,
                        text : item.name,
                        info: item.info,
                    }));
                }

                if(item.childs)
                    options(item.childs, level+1);
            }
        });

        var info = $('.step option:selected:last').attr('info');
        $('#info').val(info);
    }
    options(data, 1);

    $('.step').change(function() {
        var selected = $(this).val();
        $(this).nextAll('.step').empty();

        options(data, 1);
    });
});

<强> JSON

{"1":{"id":"1","name":"Category-1","info":"","pid":"0","childs":{"3":{"id":"3","name":"Category-1-2","info":"","pid":"1","childs":{"19":{"id":"19","name":"Captiva","info":"Some text","pid":"3"}}}}}}

依旧......

<强> PHP

foreach ($info as $key => $value) {
    $info[$value->id] = $value;
    unset($info[0]);
}

foreach($info as $key => $val)
    $childs[$val->pid][$key] = $val;

foreach($info as $item)
    if (isset($childs[$item->id]))
        $item->childs = $childs[$item->id];

$total = count($info);
foreach($info as $key => $val){
    if($info[$key]->pid != 0)
        unset($info[$key]);
}

<强> MYSQL

CREATE TABLE IF NOT EXISTS `dropdown_list` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `info` varchar(1000) NOT NULL,
  `pid` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
相关问题