How do I create a series of JS/PHP drop-down menus

2019-08-29 12:32发布

I have a tree structure in a SQL database; the tree has four levels, so every node in the Tree is in level 1, 2, or 3, and of course a single root node on level 0. Each database entry has the fields title, parentname, and level (0, 1, 2, or 3).

I want to create a series of a maximum of three drop-down boxes in an HTML form. In the beginning, the page should only display one drop-down box, populated only with the Tree nodes that are on Level 1. Choosing one of these should generate a second drop-down box, populated with all of the selected node's children (all Level 1 nodes have children). Then choosing one of those should do the same if a third drop-down is required (about half of Level 2 nodes have children nodes).

How would I go about doing this. Would I have to use PHP to generate all of the javascript on change events?

1条回答
\"骚年 ilove
2楼-- · 2019-08-29 12:54

Try testing this exact script to make sure it works, then you can tweak it. I wasn't sure if you needed it to work backwards.. i.e. changing level 1 after level 4 has been selected.

index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script>
// get a dropdown based on the parentname and level
function getDropdown(parentname, level) {
    var fields = {parentname: parentname, level: level}
    var levelspan = $('span[level='+level+']');
    // show it as loading first
    levelspan.html('Loading...');

    // use ajax to grab the next dropdown
    // based on the parentname and level
    $.get('ajax.php',fields,function(data){
        // populare the appropriate span
        // with the dropdown
        levelspan.html(data);
    });
}

// bind dropdowns on change
$('.selectDrop').live('change',function(){
    var t = $(this);

    // get the new parent and level
    var newparent = $("option:selected",this).attr('name');
    var level = t.attr('level');

    getDropdown(newparent,level);
});

$(function(){
    // load the first dropdown
    getDropdown('initialparent',0);
});

</script>

<span level='0'></span>
<span level='1'></span>
<span level='2'></span>
<span level='3'></span>

ajax.php

<?php
// here you would have SQL query that 
// grabs all the rows on $_GET['level']
// and where parentname is $_GET['parentname']
// then put them in an array called $rows
// where the key is the parentname and 
// value is the title
// i'm using a static array for testing -
$rows = array('parent1'=>'asdf','parent2'=>'awegwe','parent3'=>'3ggwg');

// get the next level
$nextLevel = $_GET['level'] + 1;

echo "<select ";
// dont bind the 4th dropdown
if ($_GET['level'] < 3) {
    echo "class='selectDrop' ";
}
echo "parentname='".$_GET['parentname']."' level='".$nextLevel."'>";
echo "<option name=''>- Level ".$nextLevel." -</option>";
foreach ($rows as $parentname => $title) {
    echo "<option name='".$parentname."'>".$title."</option>";
}
echo "</select>";
?>
查看更多
登录 后发表回答