SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 37
  1. #1
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    dynamic drop down list

    Can anyone point me to some tutorials or help me with making a dynamic drop down list ?

    What I mean is that if the user chooses "category a" in the first drop down list then the 2nd drop down gets populated with data according to "category a"

    so if he chooses "category b" the 2nd drop down list is populated with some other choices.

    Hope someone can help me with this or point me to any tutorials!

    Thanks for reading!

    //R

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    This is more of a JavaScript question - remember PHP can NOT change things on the page unless theres a refresh, or you use an AJAX request.

    There are 2 main options. Do you want to:
    a) Output all of the possible options for each box into a JavaScript array, then fire a script to change the second box on the first boxes onChange() event.

    or

    b) When the first box has been changed, send a request to the server to get all of the options depending on the value of the first box, output all of these options into <option> format and fill the second select box's innerHTML with the returned output.

    Decide which one, and I'll help you with it.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks lets try the 2nd option then

  4. #4
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ah, glad to see you picked that one. While it's more complicated, it's also much more 'fun'

    Ok, so to start off with, how is your data currently organised? is it stored in a database table, a file, a simple PHP array?

    How is the data for the second column for one option differentiated from the data for the second column with another option?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  5. #5
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I have two columns for each drop down. One contains the game brands and the other all the "armies". They are associated with their game brand by id. Im using a database

    hope that makes sense

  6. #6
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ok, so first of all you need to make a PHP page which does the following:
    • Grabs $_GET['game_id'] and queries the table for all the armies associated with that game id.
    • Outputs all of the data, each line is a new option, a comma separating text from value.
      e.g.:
      Code:
      Text1,Value1
      Text2,Value2
      Text3,Value3
      Text4,Value4
      The value is the value that is sent with the form, the text is what is shown in the select box.


    If you have trouble with that, I'll help with it.

    Then, post the code here (just so I can check it does what it should) and I'll show you how to make an AJAX request to parse that data into the selectbox.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  7. #7
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry, I got interupted here

    This is the code I got, can we use that ?

    PHP Code:
    if ($_GET['edit'] == "3") { 

    //Start Battle Stats Editor

        
    if (isset($_POST["battle_stats"])) {
        
        
    $suid $_SESSION["suid"];
        
    $game $_POST["game"];
        
    $army $_POST["army"];
        
    $vsarmy $_POST["vsarmy"];
        
    $result $_POST["result"];
        
    $points $_POST["points"];
        
    $comments $_POST["comments"];

                
    $sql mysql_query("insert into reports (report_uid, report_game, report_army, report_vsarmy, report_result, report_points, report_date, report_comments) values ('$suid','$game','$army','$vsarmy','$result','$points','$today','$comments') ")or die("Error".mysql_error());
                echo 
    "<div align='center'>Stats are updated <br />";
                echo 
    "<img src='loadbar.gif' border='0' /><br /><a href='login_success.php' target='_self'>Click here if you dont get re-directed</a></div>";
                echo 
    "<meta http-equiv='refresh' content='2;URL=login_success.php'>";
        }

        if (!isset(
    $_POST["battle_stats"])) {
            echo 
    "<form name='battle_stats' method='post' action='edit.php?edit=3'>

            <table border='0' cellspacing='0' cellpadding='5'>
              <tr>
                <td colspan='2'><select name='game' id='textfield'>
                  <option value='0' selected>Game System &gt;&gt;</option>"
    ;
                
    $sql mysql_query ("select * from armies, armyusers where armyusers.user_id=".$_SESSION["suid"]." and armyusers.army_id=armies.id ")or die();
                while (
    $row mysql_fetch_object($sql))
                {
                  echo 
    "<option value='".$row->id."'>".$row->army."</option>";
                }
            echo 
    "
                </select><input name='gamex' value='choose' id='textfield' type='submit'></td>
                <td>
                    <input name='date' type='text' size='40' id='textfield' value='"
    .$today."'>
                </td>
              </tr>
              <tr>
                <td>
          <select name='army' id='textfield'>
            <option value='0' selected>Army Name</option>"
    ;
                
    $sql mysql_query ("select * from army where army.a_game=".$_REQUEST["game"])or die();
                while (
    $row mysql_fetch_object($sql))
                {
                  echo 
    "<option value='".$row->a_id."'>".$row->a_name."</option>";
                }
            echo 
    "
                </select>        
            </td>
                <th>VS</th>
                <td>
          <select name='vsarmy' id='textfield'>
            <option value='0' selected>Army Name</option>"
    ;
                
    $sql mysql_query ("select * from army where army.a_game=".$_REQUEST["game"])or die();
                while (
    $row mysql_fetch_object($sql))
                {
                  echo 
    "<option value='".$row->a_id."'>".$row->a_name."</option>";
                }
            echo 
    "
                </select>         
            </td>
              </tr>
              <tr>
                <td colspan='2'><select name='result' id='textfield'>
                  <option value='0' selected>Result &gt;&gt;</option>
                  <option value='1'>Win</option>
                  <option value='2'>Loss</option>
                  <option value='0'>Draw</option>
                </select></td>
                <td><input name='points' type='text' id='textfield' value='Army Size'>Pts.</td>
                </tr>
              <tr>
                <td colspan='3'><textarea name='comments' cols='60' rows='30' wrap='VIRTUAL' id='comments'></textarea></td>
                </tr>
              <tr>
                <td colspan='3'><input type='reset' name='Reset' value='Reset'>
                  <input type='submit' name='battle_stats' value='Submit'></td>
              </tr>
            </table>
            
            </form>"
    ;    
        }    


  8. #8
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ok, so your page would be:
    PHP Code:
    <?php
    //---database connection/include here ---
    $sql mysql_query ("SELECT * FROM army WHERE a_game=".$_GET['game'])
    $data = array();
    while (
    $row mysql_fetch_object($sql)){
        
    $data[] = $row->a_name ',' $row->a_id;
    }
    echo 
    implode("\n"$data);
    I'll find the JavaScript you'll need and post it in a minute.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  9. #9
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    use DOM methods, innerHTML is evil :P

  10. #10
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    Thumbs up

    Ok, DOM it is

    Ok, save this as a javascript file and include it in your HTML page (by using <script type="text/javascript" src="filename.js"></script>):
    Code JavaScript:
    var xmlHttp
    var FirstSelectBox = 'Select1'; //change this to the ID of your second select box
    var SecondSelectBox = 'Select2'; //change this to the ID of your second select box
    var ScriptName = 'getarmies.php'; //change this to the name of the PHP file from before, remember that file must ONLY output the raw data, no HTML
    function changeSelect(){
    	if(FirstValue.length > 0){
    		xmlHttp = GetXmlHttpObject();
    		if (xmlHttp==null){
    			alert('Your browser doesn't support AJAX, which is required to use this site to it's full functionality');
    			return;
    		} 
    		xmlHttp.onreadystatechange=stateChanged;
    		var firstvalue = document.getElementById(FirstSelectBox).value;
    		var url = ScriptName+'?game='+firstvalue+'&sid='+Math.random();
    		xmlHttp.open('GET', url, true);
    		xmlHttp.send(null);
    	}
    } 
     
    function stateChanged(){
    	if (xmlHttp.readyState==4){
    		var response = xmlHttp.responseText;
    		var dataArray = response.split("\n");
    		var currentData;
    		document.getElementById(SecondSelectBox).options.length = 0;
    		for(var i = 0; i < dataArray.length; i++){
    			currentData = dataArray[i].split(",");
    			currentLength = document.getElementById(SecondSelectBox).options.length;
    			document.getElementById(SecondSelectBox).options[currentLength] = new Option(currentData[0], currentData[1]);
    		}
    	}
    }
     
    function GetXmlHttpObject(){
    	var xmlHttp=null;
    	try{
    		xmlHttp=new XMLHttpRequest();
    	}catch (e){
    		try{
    			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    		}catch (e){
    			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    		}
    	}
    	return xmlHttp;
    }

    Edit:

    Oh, and remember to give the select boxes IDs and put them in the above code, because the script uses the ID to access it quicker.


    and as your first selectbox:
    PHP Code:
    <select name="--name--" onChange="changeSelect()"
    It's completely untested, I just wrote it now (copied the JS from http://www.w3schools.com/ajax/ajax_source.asp and made a few major adjustments to the code), but it should work fine. Any problems just say, I'll see what's up.

    Hope that helps,
    Jake Arkinstall
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  11. #11
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    It's completely untested... but it should work fine
    You know your a programmer if...

    Unless the OP is familiar with DOM, I think it's much easier to teach someone new using innerHTML because there's less thinking involved and the javascript code is much shorter.

    Not that they shouldn't learn how to use DOM eventually.

    I would just build the whole select drop down in PHP and spit that back, and stick that inside the layer with innerHTML. The OP can learn how to use DOM to manipulate select elements later.

  12. #12
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Turns out IE doesn't support innerHTML on select boxes anyway
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  13. #13
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    That is AHAH then - Asynchronous HTTP and HTML - another stupid acronym buzzword thing :P AJAX returns XML and uses DOM methods to interpret that and act on it. Not that using one over the other particularly matters :P

    Anyway, I would suggest that you build it using method 1 (no javascript required) then use javascript to enhance it and use method 2 when it is available. You should never 'require' that a browser supports ajax to use your site.

  14. #14
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    No, what I am saying is...

    PHP Code:
     # build the entire select here..
    echo "<select name='category-b'><option></select>"
    <script>
    document.getElementById('category-b').innerHTML = ajaxObj.responseText;
    </script>

    <div id='category-b'>

    </div>

    Like that.

    Much less code and less efficient but no biggie cuz it's easier to understand.

  15. #15
    SitePoint Wizard silver trophybronze trophy Stormrider's Avatar
    Join Date
    Sep 2006
    Location
    Nottingham, UK
    Posts
    3,133
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    I know exactly what you are saying...

  16. #16
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I always prefer the object orientated method

    BlackHat, would you prefer me to make it simpler, or would you be ok with the current code?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  17. #17
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks Arkinstall. This is great for me. Lets see if I can manage to put it together now Thanks

  18. #18
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Ok, so your page would be:
    PHP Code:
    <?php
    //---database connection/include here ---
    $sql mysql_query ("SELECT * FROM army WHERE a_game=".$_GET['game'])
    $data = array();
    while (
    $row mysql_fetch_object($sql)){
        
    $data[] = $row->a_name ',' $row->a_id;
    }
    echo 
    implode("\n"$data);
    I'll find the JavaScript you'll need and post it in a minute.

    Where should I insert this code ?

    Thanks

  19. #19
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    That would be a separate PHP file.
    In the JavaScript I posted before, the default name is getarmies.php, but that's easily changed by changing the value for ScriptName in the JavaScript.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  20. #20
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok thanks. I fixed that now. So when I choose in the first select box the two others should get populated right ?

  21. #21
    SitePoint Wizard wonshikee's Avatar
    Join Date
    Jan 2007
    Posts
    1,223
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Stormrider View Post
    I know exactly what you are saying...
    My response was in reply to

    Turns out IE doesn't support innerHTML on select boxes anyway
    And just a side note, you shouldn't use a comma to separate unknown strings.

  22. #22
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    not sure what Im doing wrong, but when I choose from the first drop down nothing happends in the next

    I get a feeling that Im doing something wrong with the edit.php file where the "maincode" is

    PHP Code:
    if ($_GET['edit'] == "3") { 

    //Start Battle Stats Editor

        
    if (isset($_POST["battle_stats"])) {
        
        
    $suid $_SESSION["suid"];
        
    $game $_POST["game"];
        
    $army $_POST["army"];
        
    $vsarmy $_POST["vsarmy"];
        
    $result $_POST["result"];
        
    $points $_POST["points"];
        
    $comments $_POST["comments"];

                
    $sql mysql_query("insert into reports (report_uid, report_game, report_army, report_vsarmy, report_result, report_points, report_date, report_comments) values ('$suid','$game','$army','$vsarmy','$result','$points','$today','$comments') ")or die("Error".mysql_error());
                echo 
    "<div align='center'>Stats are updated <br />";
                echo 
    "<img src='loadbar.gif' border='0' /><br /><a href='login_success.php' target='_self'>Click here if you dont get re-directed</a></div>";
                echo 
    "<meta http-equiv='refresh' content='2;URL=login_success.php'>";
        }

        if (!isset(
    $_POST["battle_stats"])) {
            echo 
    "<form name='battle_stats' method='post' action='edit.php?edit=3'>

            <table border='0' cellspacing='0' cellpadding='5'>
              <tr>
                <td colspan='2'><select onChange='changeSelect()' name='game' id='textfield'>
                  <option value='0' selected>Game System &gt;&gt;</option>"
    ;
                
    $sql mysql_query ("select * from armies, armyusers where armyusers.user_id=".$_SESSION["suid"]." and armyusers.army_id=armies.id ")or die();
                while (
    $row mysql_fetch_object($sql))
                {
                  echo 
    "<option value='".$row->id."'>".$row->army."</option>";
                }
            echo 
    "
                </select></td>
                <td>
                    <input name='date' type='text' size='40' id='textfield' value='"
    .$today."'>
                </td>
              </tr>
              <tr>
                <td>
          <select name='army' id='army'>
            <option value='0' selected>Your army</option>
                </select>        
            </td>
                <th>VS</th>
                <td>
          <select name='vsarmy' id='vsarmy'>
            <option value='0' selected>Opponent</option>
                </select>         
            </td>
              </tr>
              <tr>
                <td colspan='2'><select name='result' id='textfield'>
                  <option value='0' selected>Result &gt;&gt;</option>
                  <option value='1'>Win</option>
                  <option value='2'>Loss</option>
                  <option value='0'>Draw</option>
                </select></td>
                <td><input name='points' type='text' id='textfield' value='Army Size'>Pts.</td>
                </tr>
              <tr>
                <td colspan='3'><textarea name='comments' cols='60' rows='30' wrap='VIRTUAL' id='comments'></textarea></td>
                </tr>
              <tr>
                <td colspan='3'><input type='reset' name='Reset' value='Reset'>
                  <input type='submit' name='battle_stats' value='Submit'></td>
              </tr>
            </table>
            
            </form>"
    ;    
        }    
    }
    //End Battle Stats Editor 

  23. #23
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The problem is that you have multiple elements with the same ID. give it the ID of 'game' and change the second and third lines in the javascript to:

    var FirstSelectBox = 'game';
    var SecondSelectBox = 'army';

    it should be fine.

    If you have more problems, is the site online?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  24. #24
    SitePoint Addict
    Join Date
    Aug 2004
    Location
    Norway
    Posts
    355
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah its online

    http://www.opponentsearch.com

    I made it to learn php, but its going slowly

    To see the stuff you help me with, you have to register, but I can setup a test account for you

  25. #25
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Hey.

    Looking at the script in FireFox/FireBug, it seems I made a pretty stupid error.

    In the JavaScript file, change
    Code javascript:
                alert('Your browser doesn't support AJAX, which is required to use this site to it's full functionality');
    to
    Code javascript:
                alert("Your browser doesn't support AJAX, which is required to use this site to it's full functionality");
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •