Options in a select element depend on selected value of another select element

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fjm
    Contributor
    • May 2007
    • 348

    Options in a select element depend on selected value of another select element

    Hello all. I am making an interface in php that will draw data from a mysql database. What I have started doing is the html, this is what I know well. php is a different story though.

    I have reached a point where I am looking at the various forms I have created and thinking about some of the drop down boxes and how the user will be able to enter the data accordingly. I have throughout the database a lot of independant tables. The purpose of these tables is to provide data to a drop down box so the user can choose the desired data. For example:

    Code:
     
    [b]district_table [/b]
    district
     
    [b]sector_table[/b]
    district
    sector
    Now, in my html, I have different input and select tags for the data. Some will be entered into the input fields and some will be used from the drop down boxes. Such as:

    Code:
     <table> 
    <tr>
    <td><select class="dated" style="width: 99%" name="sector"><option value="1" /><option value="2" /></select></td>
    </tr>
    <tr>
    <td><select class="dated" style="width: 99%" name="district"><option value="1" /><option value="2" /></select></td>
    </tr>
    </table>

    In my examples above, I need the "district" to dictate the sector. In other words, a district has many sectors but a single sector belongs to only one district.

    In order to force php to give the results of the coorasponding sectors, do I need to have dependant dropdown boxes? I hope I am making myself clear on this.

    I figured I had better get some clairification now before I waste a lot of time coding something that may not even work.

    Thanks.
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Changed thread title to better describe the problem (did you know that threads whose titles contain phrases such as 'help with' actually get FEWER responses?).

    Heya, fjm.

    If I understand what you're saying, when the User selects a value from the first drop down box, you want the values of the second drop down box to change depending on what that selected value is. Is this correct?

    There are a couple of ways of doing this. You can reload the page and handle everything via PHP, or you can use an AJAX call and take care of the display using JavaScript.

    [EDIT: As an aside, since most languages read left-to-right, it might make more sense for your Users if 'district' were on the left and 'sector' were on the right instead of the other way around.]

    Comment

    • fjm
      Contributor
      • May 2007
      • 348

      #3
      Originally posted by pbmods
      Changed thread title to better describe the problem (did you know that threads whose titles contain phrases such as 'help with' actually get FEWER responses?).
      Thanks for the advice on titleing my post. I will keep that in mind for the next time. :)

      If I understand what you're saying, when the User selects a value from the first drop down box, you want the values of the second drop down box to change depending on what that selected value is. Is this correct?
      Yes, you are correct. I need a set of dependant drop down boxes. I have googled this and have came up empty-handed. I have run across a lot of posts where people are trying to do the same thing but nobody has been successful. (At least I haven't found one yet) Lots of stuff for asp but not for php.

      There are a couple of ways of doing this. You can reload the page and handle everything via PHP, or you can use an AJAX call and take care of the display using JavaScript.
      Well, I have looked into ajax and it is out of the question for me. I have absolutely no javascript knowledge and the tutorials I have come across are not for the faint at heart. The tutorails also assume you have been programming in js for years. I really couldn't grasp any of it.

      php is different though. I would rather use php if at all possible. Is there a tutorial or a snippet you can point me to?

      As an aside, since most languages read left-to-right, it might make more sense for your Users if 'district' were on the left and 'sector' were on the right instead of the other way around.]
      Yes, your right, I just recreated that to show my html. It is actually stacked one on top of the other. Like so:

      District
      Sector

      Is there maybe an easier way to do this. Maybe without even using javascript or ajax?>

      Thanks for your help!

      Comment

      • bonski
        New Member
        • Jun 2007
        • 53

        #4
        Is there maybe an easier way to do this. Maybe without even using javascript or ajax?
        yes... you can use PHP to generate a javascript... i think javascript is essential 'cause you're dealing with forms..

        ill be back with a script.. ^___^

        Comment

        • fjm
          Contributor
          • May 2007
          • 348

          #5
          Originally posted by bonski
          yes... you can use PHP to generate a javascript... i think javascript is essential 'cause you're dealing with forms..

          ill be back with a script.. ^___^
          Hey Bonski, Thank you!!! I am *still* looking for something and haven't found anything. I did find one script that was ported to Postgres but it is above my head. There are too many things to change and my programming level is 0 at the present time. :(

          Comment

          • bonski
            New Member
            • Jun 2007
            • 53

            #6
            sorry... i was having lunch..^____^

            now.. suppose we have this tables from database.. table 1 is category and table 2 is brand... so the option in the first drop down list should return the following brands on the second drop down list if the category was selected.

            Code:
            table 1: category
            
            cat_id         cat_name
            
            1              surfing
            2              skimboarding
            3              skateboarding
            
            
            table 2: brand
            
            brand_id      cat_id        brand_name
            
            1                  2              victoria
            2                  1             quiksilver
            3                  1             billabong
            4                  3            zero skateboards
            5                  2            exile

            ok so here's the code.... i made this one.. but i modify it just now.. so that it would be clear.. ^___^.. now... save this as a php file... so if you have question just let me know.. ok... have fun...

            [PHP]//form_category.p hp
            <html>
            <head>
            <?php

            $a = 0;
            $cat_sql = "SELECT * FROM category";
            $cat_qry = mysql_query($ca t_sql);
            while($cat_row = @mysql_fetch_ar ray($cat_qry, MYSQL_ASSOC)){
            $cat_id[$a] = $cat_row['cat_id'];
            $cat_name[$a] = $cat_row['cat_name'];
            $a++;
            }

            echo '<script language="JavaS cript" type="text/JavaScript">

            function selectCategory( ){

            removeAllOption s(document.form _name.brand);';

            for($a = 0; $a<sizeof($cat_ id); $a++){

            echo 'if(document.fo rm_name.categor y.value == "'.$cat_id[$a].'"){';

            $brand_sql = "SELECT * FROM brand WHERE cat_id='".$cat_ id[$a]."'";
            $brand_qry = mysql_query($br and_sql);
            while($brand_ro w = @mysql_fetch_ar ray($brand_qry, MYSQL_ASSOC)){
            echo 'addOption(docu ment.form_name. brand,"'.$brand _row['brand_name'].'", "'.$brand_r ow['brand_name'].'");';
            }//end of while loop

            echo '}';

            }//end of for loop

            echo '
            if(document.for m_name.category .value == ""){
            removeAllOption s(document.form _name.brand);
            addOption(docum ent.form_name.b rand,"", "Select Brand");
            }';

            echo '}//end of function selectCategory( )';


            echo '
            function removeAllOption s(selectbox){

            var i;
            for(i=selectbox .options.length-1;i>=0;i--){
            selectbox.remov e(i);
            }
            }

            function addOption(selec tbox, value, text ){

            var optn = document.create Element("OPTION ");
            optn.text = text;
            optn.value = value;

            selectbox.optio ns.add(optn);
            }
            </script>';
            ?>
            </head>

            <body>

            <form name="form_name " action="" method="">
            <table>
            <tr>
            <td>
            Category: <select name="category" id="category" onChange="selec tCategory()">
            <option value="">Select Category</option>
            <?php
            $sql = "SELECT * FROM category";
            $qry = mysql_query($sq l);
            while($row = @mysql_fetch_ar ray($qry, MYSQL_ASSOC)){
            echo '<option value="'.$row['cat_id'].'">'.$row['cat_name'].'</option>';
            }
            ?>
            </select>
            </td>
            <td>
            Brands:
            <select name="brand" id="brand">
            <option value="">Select Brand</option>
            </select>
            </td>
            </tr>
            </table>
            </form>

            </body>
            </html>[/PHP]

            try to create the tables first in the database.. so that you could test this script.. and if this works.. you can change it to you desired variables... or modify the format to where you're comfortable with.. ^___^

            bonski...

            Comment

            • bonski
              New Member
              • Jun 2007
              • 53

              #7
              you can use AJAX also...to make the form look good... i mean... 'advanced'... hahahaha..

              Comment

              • fjm
                Contributor
                • May 2007
                • 348

                #8
                Originally posted by bonski
                sorry... i was having lunch..^____^
                No problem. I know how it is when you're hungry. :)

                try to create the tables first in the database.. so that you could test this script.. and if this works.. you can change it to you desired variables... or modify the format to where you're comfortable with.. ^___^

                bonski...
                I recreated the tables exactly as you had them. The first dropdown box populates with the data but the second does not. It is just empty. What I noticed was that when I chose the second box there was no network communication what so ever. The onchange doesn't seem to be working. The page is not refreshing at all.

                Would you have any suggestions? I figure since there are 2 boxes, we are 50% done. :)

                Thanks a million for the code and the help Bonski!

                Frank

                Comment

                • fjm
                  Contributor
                  • May 2007
                  • 348

                  #9
                  Originally posted by bonski
                  you can use AJAX also...to make the form look good... i mean... 'advanced'... hahahaha..
                  Bonski.. If I had ANY idea idea that ajax would be so useful to me, I would have learned javascript a long time ago! I really missed out on that one.

                  Yes, advanced is the word. I love ajax. I went to w3schools.com and actually started to learn javascript because ajax requires a working knowledge of js first.

                  How long do you think it would take me to learn js?

                  Comment

                  • Purple
                    Recognized Expert Contributor
                    • May 2007
                    • 404

                    #10
                    Hi

                    going back to pbmods other suggestion of doing the second select in PHP, one way to implement this using an absolute minimum of javascript is like so:

                    change your first select html statement to add add an onchange event

                    [PHP]echo "<select name=\"district \" onChange=\"java script:refresh_ win('select_sec tor');\"";[/PHP]

                    ensure the form calls itself onsubmit using

                    <form name='FORM_NAME ' method='POST or GET' action="<?php echo $_SERVER["PHP_SELF"] ?>;

                    add a submit button to your form called submit if you have not got one already which is on the form as you select the district

                    and add this javascript to the code.

                    Code:
                    function refresh_win(form_name)
                    {
                    	document[form_name].submit.click();
                    }
                    I generally run a collection of client side scripts in my projects to allow reuse and simplify maintenance which is why it is generalised - you could simplify it further and have it within the form body..

                    as a side note - if you have problems getting it working and everything looks ok, just check the html within the form is ok - some browsers will throw a big wobbler with the javascript if you don't close certain tags properly but the form will look ok when run.

                    Regards Purple

                    Comment

                    • bonski
                      New Member
                      • Jun 2007
                      • 53

                      #11
                      Originally posted by fjm
                      Bonski.. If I had ANY idea idea that ajax would be so useful to me, I would have learned javascript a long time ago! I really missed out on that one.

                      Yes, advanced is the word. I love ajax. I went to w3schools.com and actually started to learn javascript because ajax requires a working knowledge of js first.

                      How long do you think it would take me to learn js?
                      im sorry.. the script i post had error on line 27... its just a typo... change this line

                      [PHP]while($brand_ro w = @mysql_fetch_ar ray($brand_row, MYSQL_ASSOC)){[/PHP]

                      to this one...

                      [PHP]while($brand_ro w = @mysql_fetch_ar ray($brand_qry, MYSQL_ASSOC)){[/PHP]

                      then its ok.... sorry about that.. i was too careless.. hahaha.. anyway that will work..


                      bonski

                      Comment

                      • fjm
                        Contributor
                        • May 2007
                        • 348

                        #12
                        Originally posted by Purple
                        Hi

                        going back to pbmods other suggestion of doing the second select in PHP, one way to implement this using an absolute minimum of javascript is like so:

                        change your first select html statement to add add an onchange event

                        [PHP]echo "<select name=\"district \" onChange=\"java script:refresh_ win('select_sec tor');\"";[/PHP]

                        ensure the form calls itself onsubmit using

                        <form name='FORM_NAME ' method='POST or GET' action="<?php echo $_SERVER["PHP_SELF"] ?>;

                        add a submit button to your form called submit if you have not got one already which is on the form as you select the district

                        and add this javascript to the code.

                        Code:
                        function refresh_win(form_name)
                        {
                        	document[form_name].submit.click();
                        }
                        I generally run a collection of client side scripts in my projects to allow reuse and simplify maintenance which is why it is generalised - you could simplify it further and have it within the form body..

                        as a side note - if you have problems getting it working and everything looks ok, just check the html within the form is ok - some browsers will throw a big wobbler with the javascript if you don't close certain tags properly but the form will look ok when run.

                        Regards Purple
                        :( I can't get this thing to work. I tried purple.. I just get this:

                        Code:
                         function selectCategory(){ removeAllOptions(document.form_name.brand);if(document.form_name.category.value == "1"){}if(document.form_name.category.value == "2"){} if(document.form_name.category.value == ""){ removeAllOptions(document.form_name.brand); addOption(document.form_name.brand,"", "Select Brand"); }}//end of function selectCategory() function removeAllOptions(selectbox){ var i; for(i=selectbox.options.length-1;i>=0;i--){ selectbox.remove(i); } } function addOption(selectbox, value, text ){ var optn = document.createElement("OPTION"); optn.text = text; optn.value = value; selectbox.options.add(optn); }

                        Comment

                        • fjm
                          Contributor
                          • May 2007
                          • 348

                          #13
                          Originally posted by bonski
                          im sorry.. the script i post had error on line 27... its just a typo... change this line

                          [PHP]while($brand_ro w = @mysql_fetch_ar ray($brand_row, MYSQL_ASSOC)){[/PHP]

                          to this one...

                          [PHP]while($brand_ro w = @mysql_fetch_ar ray($brand_qry, MYSQL_ASSOC)){[/PHP]

                          then its ok.... sorry about that.. i was too careless.. hahaha.. anyway that will work..


                          bonski
                          Bonski...... You be DA MAN!!!!!!!!!!! :) :) :) :)

                          Listen.. stupid question for you but.. how long did it take you to learn php? I'm trying to figure out how long I will have to suffer before things get clearer . :)

                          Comment

                          • fjm
                            Contributor
                            • May 2007
                            • 348

                            #14
                            @ Purple,

                            Can I use your code to post my data to the database? I have not yet figured out how to actually submit the data. I have the button but that's about it. haha... Nothing that drives the button.

                            It looks like to me that if I use your code, I can post the data using a database script and then will return to the same screen. Am I correct on this?

                            Comment

                            • bonski
                              New Member
                              • Jun 2007
                              • 53

                              #15
                              Originally posted by fjm
                              Bonski...... You be DA MAN!!!!!!!!!!! :) :) :) :)

                              Listen.. stupid question for you but.. how long did it take you to learn php? I'm trying to figure out how long I will have to suffer before things get clearer . :)
                              hey i PM the answer.. check your inbox... hahahahaa...

                              Comment

                              Working...