Controlled/Dependent Lists - for experts ;)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • coool
    New Member
    • Aug 2007
    • 67

    #1

    Controlled/Dependent Lists - for experts ;)

    Hi

    I'm now trying to have a dependent lists in a form

    my form is a query based form

    i.e. I fill my MySQL query from this form

    I have around 30 fields/columns

    each have number of values... sometimes 2 , sometimes 20.. maybe more !

    I've searched the web to find a javascript code that helps me to do the dependent lists

    I found few funtions.. but their work depends on INDEX !

    they're very powerful functions.. i liked them.. but didn't know how to modify them until i get what i'm looking for

    This is what I've found ( in two diff websites) - it's working if you copied it and pasted then tried it !
    [code=html]
    <html>
    <head>
    <script type="text/javascript">
    function DepSelectOne(ma sterSelect){
    var frm = masterSelect.fo rm;
    this.selectedBl ock = 0;
    this.selBoxes = new Array(masterSel ect);
    if((frm)&&(type of Option != 'undefined')){
    for(var c = 1;c < arguments.lengt h;c++){
    var selObj = frm[arguments[c]];
    if((selObj)&&(s elObj.type.inde xOf('select') == 0)&&(selObj.typ e.indexOf('mult ') < 0)&&(selObj.opt ions.length > 2)){
    this.selBoxes[this.selBoxes.l ength] = frm[arguments[c]];
    }
    }
    if((this.selBox es.length >1)&&(this.selB oxes.length == arguments.lengt h)){
    this.selectElem ent = this.selBoxes[0];
    DepSelectOne.in st[this.index = this.selectElem ent.name] = this; //keep global record of this object instance.
    this.selBoxes[0] = this;
    this.optionBloc k = new OptionBlock(0, this.selectElem ent, this.selectElem ent.options[0].value, this, 0);
    this.next = new DepSelectOneNex t(this.selBoxes , 1);
    this.next.setSe lection(this.op tionBlock.getSe lection());
    this.selectElem ent.onchange = new Function('DepSe lectOne.inst[\''+this.index+ '\'].handleChange(0 )');
    }else{
    //alert('DepSelec tOne constructor could not find\nsufficien t properly configured SELECT elements\nto initialise.');
    }
    }
    }
    DepSelectOne.in st = {}; //Globally accessible object to hold instances of the DepSelectOne Class.
    //call chain terminating functions.
    DepSelectOne.pr ototype.validat eNext = DepSelectOne.pr ototype.reset = DepSelectOne.pr ototype.setSele ction = DepSelectOne.pr ototype.setSele ctedFromChild = function(){retu rn true;}
    DepSelectOne.pr ototype.validat e = function(){
    return ((this.optionBl ock.lastSelecti on < 0)?false:this.n ext.validateNex t());
    }
    DepSelectOne.pr ototype.init = function(select edBlock){
    if(selectedBloc k >= 0){
    this.optionBloc k.lastSelection = selectedBlock;
    }
    if(this.optionB lock.lastSelect ion >= 0){
    this.optionBloc k.doElement();
    if(window.setTi meout)setTimeou t('DepSelectOne .inst[\''+this.index+ '\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
    }
    }
    DepSelectOne.pr ototype.handleC hange = function(ind){
    this.selBoxes[ind].changed();
    if(window.setTi meout)setTimeou t('DepSelectOne .inst[\''+this.index+ '\'].refresh();', 5); //fix for Opera 7 timing problem. Harmless otherwise.
    }
    DepSelectOne.pr ototype.refresh = function(){
    this.selectElem ent.selectedInd ex = this.optionBloc k.lastSelection ;
    this.next.reset ();
    }
    DepSelectOne.pr ototype.changed = function(){
    this.optionBloc k.readState();
    this.next.setSe lection(this.op tionBlock.getSe lection());
    }

    function DepSelectOneNex t(selBoxes, selBoxIndex){
    this.selectedBl ock = -1;
    this.classObj = selBoxes[0];
    this.previous = selBoxes[(selBoxIndex-1)]
    this.selectElem ent = selBoxes[selBoxIndex];
    selBoxes[selBoxIndex] = this;
    this.selectElem ent.onchange = new Function('DepSe lectOne.inst[\''+this.classO bj.index+'\'].handleChange(' +selBoxIndex+') ');
    this.seperatorO ption = new DepOption(this. selectElement.o ptions[0]);
    this.optionBloc ks = [];
    var startIndex = 1;
    while(startInde x < this.selectElem ent.options.len gth){
    var nextIndex = this.optionBloc ks.length;
    this.optionBloc ks[nextIndex] = new OptionBlock(sta rtIndex, this.selectElem ent, this.selectElem ent.options[0].value, this, nextIndex);
    startIndex += this.optionBloc ks[nextIndex].getOptionsTota l();
    }
    for(var cnt = 0,c = 0;c < this.optionBloc ks.length;c++){
    this.optionBloc ks[c].blockStart = cnt;
    cnt += this.optionBloc ks[c].getItems();
    }
    if(++selBoxInde x < selBoxes.length ){
    this.next = new DepSelectOneNex t(selBoxes, selBoxIndex);
    }else{
    this.next = this.classObj;
    this.previous.i nit(this.select edBlock);
    }
    }
    DepSelectOneNex t.prototype.res et = function(){
    if((this.select edBlock >= 0)&&(this.optio nBlocks[this.selectedBl ock].lastSelection >= 0)){
    this.selectElem ent.selectedInd ex = this.optionBloc ks[this.selectedBl ock].lastSelection;
    this.next.reset ();
    }
    }
    DepSelectOneNex t.prototype.set Selection = function(selBlo ck){
    this.selectedBl ock = selBlock;
    if(this.selecte dBlock < 0){
    var opt = this.selectElem ent.options;
    opt.length = 0; //clear options
    opt[0] = this.seperatorO ption.getOption ();
    this.selectElem ent.selectedInd ex = 0;
    this.next.setSe lection(-1);
    }else{
    var blk = this.optionBloc ks[this.selectedBl ock];
    blk.doElement() ;
    this.next.setSe lection(blk.get Selection());
    }
    }
    DepSelectOneNex t.prototype.cha nged = function(){
    if(this.selecte dBlock >= 0){
    var blk = this.optionBloc ks[this.selectedBl ock];
    blk.readState() ;
    this.next.setSe lection(blk.get Selection());
    }
    }
    DepSelectOneNex t.prototype.set SelectedFromChi ld = function(blockI ndex){
    if(this.selecte dBlock < 0){ //only set from OptonBlock on the first attempt.
    this.selectedBl ock = blockIndex;
    }
    }
    DepSelectOneNex t.prototype.ini t = function(selBlo ck){
    if(selBlock >= 0){
    var blockIndex = 0;
    while(!this.opt ionBlocks[blockIndex++].nextBlockTest( selBlock));
    }
    this.previous.i nit(this.select edBlock);
    }
    DepSelectOneNex t.prototype.val idateNext = function(){
    return (((this.selecte dBlock < 0)||(this.optio nBlocks[this.selectedBl ock].lastSelection < 0))?false:this. next.validateNe xt());
    }

    function DepOption(optEl ){
    this.value = optEl.value;
    this.text = optEl.text;
    }
    DepOption.proto type.getOption = function(){
    return new Option(this.tex t, this.value);
    }

    function OptionBlock(sta rtIndex, selectElement, seperatorValue, owner, blockIndex){
    this.blockStart = 0;
    this.owner = owner;
    this.index = blockIndex;
    this.selectElem ent = selectElement;
    this.seperators = [];
    this.optionBloc k = [];
    this.lastSelect ion = -1;
    var opts = this.selectElem ent.options;
    while((startInd ex < opts.length)&&( opts[startIndex].value == seperatorValue) ){
    this.seperators[this.seperators .length] = new DepOption(opts[startIndex++]);
    }
    while((startInd ex < opts.length)&&( opts[startIndex].value != seperatorValue) ){
    if((this.lastSe lection < 0)&&(opts[startIndex].selected == true)){
    this.lastSelect ion = this.optionBloc k.length; //record first item selected, if any.
    }
    this.optionBloc k[this.optionBloc k.length] = new DepOption(opts[startIndex++]);
    }
    if(this.lastSel ection >= 0)this.owner.se tSelectedFromCh ild(this.index)
    }
    OptionBlock.pro totype.getOptio nsTotal = function(){
    return (this.seperator s.length + this.optionBloc k.length);
    }
    OptionBlock.pro totype.getItems = function(){
    return this.optionBloc k.length;
    }
    OptionBlock.pro totype.nextBloc kTest = function(selBlo ck){
    if((selBlock >= this.blockStart )&&(selBlock < this.blockStart +this.optionBlo ck.length)){
    this.lastSelect ion = selBlock - this.blockStart ;
    this.owner.sele ctedBlock = this.index;
    return true;
    }
    return false;
    }
    OptionBlock.pro totype.getSelec tion = function(){
    return ((this.lastSele ction < 0)?-1:(this.blockSt art+this.lastSe lection));
    }
    OptionBlock.pro totype.doElemen t = function(){
    var opt = this.selectElem ent.options;
    opt.length = 0; //clear options
    if((this.lastSe lection < 0)&&(this.seper ators.length > 0)){
    opt[opt.length] = this.seperators[(this.seperator s.length-1)].getOption();
    }
    for(var c = 0;c < this.optionBloc k.length;c++){
    opt[opt.length] = this.optionBloc k[c].getOption();
    }
    this.selectElem ent.selectedInd ex = ((this.lastSele ction < 0)?0:this.lastS election);
    }
    OptionBlock.pro totype.readStat e = function(){
    if(this.lastSel ection < 0){
    this.lastSelect ion = (this.selectEle ment.selectedIn dex - 1);
    this.doElement( );
    }else{
    this.lastSelect ion = this.selectElem ent.selectedInd ex;
    }
    }
    </script>
    </head>
    <body onload="new DepSelectOne(do cument.forms['StateCityForm'].elements['State'], 'City');">

    <form name="StateCity Form" ACTION="" METHOD="GET" TARGET="_blank" >

    First Choose State: &nbsp;
    <select name="State">
    <option value="choose"> choose one</option>
    <option value="State_1" >State 1</option>
    <option value="State_2" >State 2</option>
    <option value="State_3" >State 3</option>
    </select><br><br>

    Now Select City: &nbsp;
    <select name="City">
    <option value="choose"> &lt;select previous first</option>
    <option value="choose"> select City for State_1</option>
    <option value="City_A__ State_1" >City A of State 1</option>
    <option value="City_B__ State_1" >City B of State 1</option>
    <option value="City_C__ State_1" >City C of State 1</option>
    <option value="City_D__ State_1" >City D of State 1</option>
    <option value="City_E__ State_1" >City E of State 1</option>
    <option value="City_F__ State_1" >City F of State 1</option>

    <option value="choose"> select City for State_2</option>
    <option value="City_A__ State_2" >City A of State 2</option>
    <option value="City_B__ State_2" >City B of State 2</option>

    <option value="choose"> select City for State_3</option>
    <option value="City_A__ State_3" >City A of State 3</option>
    <option value="City_B__ State_3" >City B of State 3</option>
    <option value="City_C__ State_3" >City C of State 3</option>
    <option value="City_D__ State_3" >City D of State 3</option>
    </select>

    </form>

    </body>
    </html>
    [/code]

    this above code - is done with index.. i can't list all of mysql table values !!

    let me tell you what i would like to do:

    in the options of first list their should be this code:
    this code will show fields available in the mysql table
    [php]
    <?
    $sql = "SHOW FIELDS FROM myTable";
    $result = mysql_query($sq l);

    while($row = mysql_fetch_row ($result))
    {?>
    <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
    <?}
    ?>
    [/php]

    NOW .. to show values of ONE field (second list)
    i use this code:
    [php]
    <?
    $sql = "Select filed2 FROM myTable GROUP BY filed2";
    $result = mysql_query($sq l);

    while($row = mysql_fetch_row ($result))
    {?>
    <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
    <?}
    ?>
    [/php]

    In the above code, what i want is to have field2 be different depending on what user has selected in the first list

    is there something like !! .. if user select item in the first list - take this item and assign it to field ?? ( so I'll use in my above code $field instead of field2 ) !!!

    please help me.. I feel i'm almost there finding the right solution for this problem.. but need some help from you guys :)

    P.S.1. I don't want to submit twice in the form i.e. i don't wonna sumbit first list so second list should be assigned.. i've tried that and made some other problems in my form

    P.S.2. I don't want to use AJAX - .. what i need is php/html/javascript

    Thanks in advance :)
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    You are hacking somebody elses code to produce a solution in one go.
    Fine if you know what you are doing.
    Break this project into simple steps and solve each problem in turn.
    You surely don't expect us to wade through this lot and make it work like you are expecting?

    Comment

    • coool
      New Member
      • Aug 2007
      • 67

      #3
      well, I found this code in two places.. and they said there to readers to look at the webpage source - i.e. they gave the permission to do that

      I posted the code here so you guys can understand easily what I'm talking about

      this is not many problems together - it's only one problem called (controlled/dependent 2 lists) where what's selected in one list should be used in mysql query in the second list to get the values of the first list selection

      Comment

      • pbmods
        Recognized Expert Expert
        • Apr 2007
        • 5821

        #4
        Heya, coool.

        So the idea is to have two select elements, and when you select anything from the first select, the second select gets populated depending on what you picked. Does that sound right?

        Comment

        • coool
          New Member
          • Aug 2007
          • 67

          #5
          yes that's exactly what I'm looking for..

          similar to countries and cities -- if someone selects a country - then in the second list cities of that country should be shown only

          in both select statements i should populate the options in a query similar to the last two portion of codes in my first post

          but i don't want to submit twice in the form - and i don't want to use AJAX -- is there any other solution !! --- maybe some code in javascript can help !

          Comment

          • coool
            New Member
            • Aug 2007
            • 67

            #6
            do you remember my thread called " Dynamic Condition "
            ==> http://www.thescripts.com/forum/thread691489.html

            I'm actually wonna apply the controlled/dependent lists to that code

            i.e. after choosing the field --- user will see in the next select statement only the values of that selected field (grouped by to have no duplicates

            for fields:
            [php]
            <?
            $sql = "SHOW FIELDS FROM myTable";
            $result = mysql_query($sq l);

            while($row = mysql_fetch_row ($result))
            {?>
            <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
            <?}
            ?>
            [/php]

            for values:
            [php]
            <?
            $sql = "Select $field FROM myTable GROUP BY $field";
            $result = mysql_query($sq l);

            while($row = mysql_fetch_row ($result))
            {?>
            <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
            <?}
            ?>
            [/php]

            Comment

            • jx2
              New Member
              • Feb 2007
              • 228

              #7
              "like countries and cities" so why you dont do it!!
              [html]<!DOCTYPE html
              PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
              <html>
              <head>
              <title>simple document</title>
              <script language='javas cript'><!--

              //=============== == generate in PHP =============== =============== =======
              countries = new Array();
              countries["usa"]= new Array("New York","Chicago" );
              countries["england"]= new Array("london", "bristol");
              //=============== == end of PHP generated script =============== =============== =

              function secondList(coun try){
              var a = countries[country];
              newListHTML='<s elect>';
              for( city in a){
              newListHTML+='< option value="'+a[city]+'">'+a[city]+'</option>';
              }
              newListHTML+='</select>';
              document.getEle mentById('newLi stDiv').innerHT ML= newListHTML;
              }
              -->
              </script>
              </head>
              <body>
              <form action="vartree .php" method='POST'>

              <select name="firstList " onchange="secon dList(this.valu e)">
              <option value=''></option>
              <option value='england' >england</option>
              <option value='usa'>usa </option>
              </select>
              <div id='newListDiv' ></div>
              </form>
              </body>
              </html>[/html]
              did you mean something like that?

              regards
              jx2

              Comment

              • coool
                New Member
                • Aug 2007
                • 67

                #8
                your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !

                so from your code - i've wrote some code - but it didn't work as I need to use the value of the first field in a php code (mysql for the second list)

                [php]
                <script language='javas cript'>
                function secondList(fiel d)
                {
                newListHTML= '$sql = "SELECT 'field' FROM myTable GROUP BY 'field'"';
                document.getEle mentById('newLi stDiv').innerHT ML= newListHTML;
                }
                </script>
                </head>

                <body>

                <form action="" method='POST'>
                <select name="firstList " onchange="secon dList(this.valu e)">
                <option value=''></option>
                <?
                $sql = "SHOW FIELDS FROM myTable";
                $result = mysql_query($sq l);

                while($row = mysql_fetch_row ($result))
                {?>
                <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
                <?}
                ?>
                </select>

                <div id='newListDiv' >
                <select>
                <?
                $result = mysql_query($sq l);

                while($row = mysql_fetch_row ($result))
                {?>
                <option value="<?echo $row[0]?>"><?echo $row[0]?></option>
                <?}
                ?>
                </select>
                </div>
                </form>
                [/php]

                what do you think ? can't this above code be fixed somehow !

                Comment

                • jx2
                  New Member
                  • Feb 2007
                  • 228

                  #9
                  Originally posted by coool
                  your code depends on Arrays - but I can't put all of my fields with all of thier unique values in arrays because they are many - approx. of 30 fields with each have between 2 unique values and 50 unique values - maybe more !
                  and? whats the problem? juzt use morte arrays :-)
                  [quoate[can't this above code be fixed somehow ![/QUOTE]
                  yes it can be - honestly i think is almost done - i cant do it for you
                  1 u have to learn
                  2 i have no idea what you really need
                  3 i am not payed ;-)
                  4 i helped you as much as is needed

                  regards
                  jx2

                  Comment

                  • pbmods
                    Recognized Expert Expert
                    • Apr 2007
                    • 5821

                    #10
                    Heya, coool.

                    The thing about PHP is that it doesn't "talk" to the browser the way that JavaScript does.

                    The general flow of a web request is:
                    • The browser sends a request to the server.
                    • The server loads the requested page and decides what to do with it.
                    • In the case of a PHP script, it runs the script by PHP and sends the result to the browser.
                    • The server closes the completed request and then waits patiently for the next one.


                    Note that once the server sends the page to the client's browser, that's it; to get any more data from the server, you have to send a request for another page. This is the idea behind AJAX; it allows you to send a new request without having to load a new page.

                    If you want to be able to load a set of data without connecting to the server first, then you have to have loaded that data when you first opened the page. So for example, if you want to populate a select element from a MySQL result set, you have to either:
                    • connect to the server again by using AJAX or submitting a form, or
                    • have already loaded that data as part of the HTML / JavaScript.


                    This is what JX2 is trying to get at in his posts.

                    You can use PHP to format your MySQL result set as a JavaScript object and output that as part of the page.

                    For example:
                    [code=php]
                    $sql = "
                    SELECT
                    DISTINCT
                    `countries`.`na me`
                    AS `country`,
                    `cities`.`name`
                    AS `city`
                    FROM
                    (
                    `countries`
                    LEFT JOIN
                    `cities`
                    USING
                    (`countryid`)
                    )
                    ORDER BY
                    `countries`.`na me` ASC,
                    `cities`.`name` ASC";
                    $res = mysql_query($sq l);

                    $data = array();

                    while($row = mysql_fetch_ass oc($res))
                    {
                    $data[$row['country']][] = $row['city'];
                    }

                    echo json_encode($da ta);
                    [/code]

                    You end up with something very similar to what JX2 proposed as your output.

                    The other option would be to use AJAX (I promise it's not nearly as scary as it sounds!).

                    Comment

                    • coool
                      New Member
                      • Aug 2007
                      • 67

                      #11
                      okay from your useful comments :) I'm really near from the final correct solution

                      now i have a big Array that have all fields and inside this array i have a sub array for each field to present a unique values

                      my problem now with how to use 2-dim array in javascript

                      here's the code i reached unitl now:
                      [code=javascript]
                      <script language='javas cript'>

                      function secondList(fiel d)
                      {
                      var value;
                      var content = new Array();
                      content = data[field][];
                      newListHTML='<s elect>';
                      for(value in content)
                      {
                      newListHTML+='< option value="'+conten t[value]+'">'+content[value]+'</option>';
                      }
                      newListHTML+='</select>';
                      document.getEle mentById('newLi stDiv').innerHT ML= newListHTML;
                      }
                      </script>
                      [/code]

                      here's how the data look like of my array:
                      array name: $data[][]
                      Code:
                      Array
                      (
                      
                          [field1] => Array
                              (
                                  [0] => value1
                                  [1] => value2
                              )
                          [field2] => Array
                              (
                                  [0] => value1
                                  [1] => value1
                                  [2] => value1
                                  [3] => value1
                                  [4] => value1
                              )
                      .....................................................etc
                      }
                      I can't get the javascript array working ! .. do you have any clue where is my mistake in the code ? !

                      Comment

                      • pbmods
                        Recognized Expert Expert
                        • Apr 2007
                        • 5821

                        #12
                        Heya, coool.

                        Where do you create the JavaScript data object?

                        Comment

                        • coool
                          New Member
                          • Aug 2007
                          • 67

                          #13
                          Oh ! --- should i create it inside my javascript !! how !

                          data is here inside the php code:

                          [php]
                          $sql1 = "SHOW FIELDS FROM TableOne";
                          $res1 = mysql_query($sq l1);
                          $data = array();

                          while($row1 = mysql_fetch_row ($res1))
                          {
                          $sql2 = "SELECT ".$row1[0]." FROM TableOne GROUP BY ".$row1[0];
                          $res2 = mysql_query($sq l2);
                          while($row2 = mysql_fetch_row ($res2))
                          {
                          $data[$row1[0]][] = $row2[0];
                          }
                          }
                          [/php]

                          when I do this:
                          [php]
                          echo "<pre>";
                          print_r($data);
                          echo "</pre>";
                          [/php]
                          ,I get this output:
                          Code:
                          Array
                          (
                              [field1] => Array
                                  (
                                      [0] => value1
                                      [1] => value2
                                  )
                              [field2] => Array
                                  (
                                      [0] => value1
                                      [1] => value1
                                      [2] => value1
                                      [3] => value1
                                      [4] => value1
                                  )
                          ..................................................  ...etc
                          }

                          Comment

                          • coool
                            New Member
                            • Aug 2007
                            • 67

                            #14
                            i looked at jx2 code !

                            when he/she created countries array, he didn't declare it inside the javascript !

                            similar to this , i've created " data " in php and then used it in javascript !

                            am i wrong :) ?

                            Comment

                            • jx2
                              New Member
                              • Feb 2007
                              • 228

                              #15
                              Originally posted by coool
                              i looked at jx2 code !

                              when he/she created countries array, he didn't declare it inside the javascript !

                              similar to this , i've created " data " in php and then used it in javascript !

                              am i wrong :) ?
                              i am HE :-)
                              you are wrong
                              i did declare array in javascript
                              and expected that you create this javascript/arrays in php (in php you can create dynamicly javascript code)

                              but lets be honest as PBmods sugested thats the job for ajax (to be honest thats the simliest and niciest solution in this case)

                              jx2

                              Comment

                              Working...