How Do I Create A Series Of Js/php Drop-down Menus That Automatically Populate Based On A Sql Tree?
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 en
Solution 1:
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
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script><script>// get a dropdown based on the parentname and levelfunctiongetDropdown(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 levelvar newparent = $("option:selected",this).attr('name');
var level = t.attr('level');
getDropdown(newparent,level);
});
$(function(){
// load the first dropdowngetDropdown('initialparent',0);
});
</script><spanlevel='0'></span><spanlevel='1'></span><spanlevel='2'></span><spanlevel='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 dropdownif ($_GET['level'] < 3) {
echo"class='selectDrop' ";
}
echo"parentname='".$_GET['parentname']."' level='".$nextLevel."'>";
echo"<option name=''>- Level ".$nextLevel." -</option>";
foreach ($rowsas$parentname => $title) {
echo"<option name='".$parentname."'>".$title."</option>";
}
echo"</select>";
?>
Post a Comment for "How Do I Create A Series Of Js/php Drop-down Menus That Automatically Populate Based On A Sql Tree?"