www.webdeveloper.com
Results 1 to 12 of 12

Thread: problem with dynamic dropdown list

  1. #1
    Join Date
    Sep 2009
    Posts
    18

    problem with dynamic dropdown list

    I have a script that contains 3 dropdown list. 1 country 2 region 3 city
    I wonder how i can populate the script from database
    because if i leave it like this works fine but i want to extract the country from database mysql. if somebody knows how can i do that please help.

  2. #2
    Join Date
    Sep 2009
    Location
    Wisconsin
    Posts
    15
    This cannot be acheived with Javascript you must use PHP to access your Mysql database to create the dropdown list.

    PHP Code:
    function createDropDownList() {
     
    $mysqli mysqli_connect("host""un""pw""db");
     
    $dbname 'database';
     
    $sql "SHOW TABLES FROM $dbname";
     
    $result mysqli_query($mysqli$sql);
     echo 
    "<select name'selectName'>";
     while (
    $row mysqli_fetch_array($result)) {
       
    $tempCounter 0;
       echo 
    "<option value='".$row[$tempCounter]."'>".ucfirst($row[$tempCounter])."</option<br/>";
     } 
     echo 
    "</select>";
     } 
    This would work if you had a table for each country name. I'm not sure if I'm understanding your question right. Are you trying to use Ajax methods to get the dropdown to update? Even with Ajax you will still need PHP to access the DB.

  3. #3
    Join Date
    Sep 2009
    Posts
    18
    let me ask again. I have this dropdown lists that are populate from an external file called countryCityList.php where i have array from each country and i want to populate this list from that array only that I want this array to have the data from database. Tha data are from a table called members where i have country region and city.
    This are the lists:
    CODE:

    <form id="form1" name="form1" method="post" action="registration2.php">
    <table width="100%" border="0" cellpadding="6" cellspacing="20">
    <tr>
    <td><div align="right">
    <label for="country">Your Country</label>
    </div></td>
    <td><div align="left">

    <select style="width: 15em" name="country" id="country" onchange="setStates();">
    <option selected="selected">Select your Country</option>
    <option value="Germany">Germany</option>
    <option value="Morocco">Morocco</option>
    <option value="United Kingdom">United Kingdom</option>
    </select>
    </div></td>
    </tr>
    <tr>
    <td><div align="right">
    <label for="label">Your Region</label>
    </div></td>
    <td>
    <div align="left">

    <select style="width: 15em" name="region" id="region" onchange="setCities();">
    <option selected="selected">Select your Region</option>
    </select>
    </div></td>
    </tr>
    <tr>
    <td><div align="right">
    <label for="city">Your City</label>
    </div></td>
    <td><div align="left">

    <select style="width: 15em" name="city" id="city">
    </select>
    </div></td>

    And this the external file where i want to have the arrays from the database if this could happen:
    CODE:

    var states = new Array();


    states['Germany'] = new Array('Bayern','Berlin','Hamburg');
    states['Morocco'] = new Array('Casablanca','Doukkala Abda','Guelmin');
    states['United Kingdom'] = new Array('England','Scotland','Wales','Northern Ireland');


    // City lists
    var cities = new Array();

    cities['Germany'] = new Array();

    cities['Germany']['Bayern'] = new Array('Ainring');
    cities['Germany']['Berlin'] = new Array('Berlin');
    cities['Germany']['Hamburg'] = new Array('Hamburg');

    cities['Morocco'] = new Array();
    cities['Morocco']['Casablanca'] = new Array('ad-Dar-al-Baida');
    cities['Morocco']['Doukkala Abda'] = new Array('al-Jadidah');
    cities['Morocco']['Guelmin'] = new Array('Gulimim');

    cities['United Kingdom'] = new Array();

    cities['United Kingdom']['England'] = new Array('Abingdon');
    cities['United Kingdom']['Scotland'] = new Array('Alford');
    cities['United Kingdom']['Wales'] = new Array('Maesteg');
    cities['United Kingdom']['Northern Ireland'] = new Array('Coleraine');

    function setStates() {
    cntrySel = document.getElementById('country');
    stateList = states[cntrySel.value];
    changeSelect('region', stateList, stateList);
    setCities();
    }

    function setCities() {
    cntrySel = document.getElementById('country');
    stateSel = document.getElementById('region');
    if (typeof(cities[cntrySel.value]) == 'undefined') {
    cityList = new Array('<Select your city>');
    }
    else {
    cityList = cities[cntrySel.value][stateSel.value];
    }
    changeSelect('city', cityList, cityList);
    }

    function changeSelect(fieldID, newOptions, newValues) {
    selectField = document.getElementById(fieldID);
    selectField.options.length = 0;
    // if (typeof(newOptions) == 'undefined') {
    if (fieldID == 'region') {
    selectField.options[0] = new Option("<Select your region>", null);
    }
    if (fieldID == 'city') {
    selectField.options[0] = new Option("<Select your city>", null);
    }
    // }
    // else {
    if (typeof(newOptions) != 'undefined') {
    for (i=0; i<newOptions.length; i++) {
    selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
    }
    }
    // }

    }

    function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
    window.onload = func;
    } else {
    window.onload = function() {
    if (oldonload) {
    oldonload();
    }
    func();
    }
    }
    }

    addLoadEvent(function() {
    setStates();
    });

    Please help me if you can.
    Regards!

  4. #4
    Join Date
    Sep 2009
    Location
    Wisconsin
    Posts
    15
    Well, PHP and Javascript don't go together. As far as I know you can't access a database with javascript, it's possible I'm wrong on this though. From my knowledge you would not be able to accomplish what you are asking because you need to have the PHP access the database. If someone else has a way to do this please reply on this thread so I may learn as well.

    Thanks.

  5. #5
    Join Date
    Sep 2009
    Posts
    18
    Ok. Thanks for this reply. Well if i am connecting to database and extract data like this:
    Code:
    <?php
    $sql="SELECT country FROM members";
    $result =mysql_query($sql);
    while ($country=mysql_fetch_assoc($result)){
    ?>
    <option value ="<?php echo $country['id'] ?>" >
    <?php echo $country['country'] ?>
    </option>
    <?php } ?>

    how can i put that data to this array
    Code:

    var states = new Array();

    states['Germany'] = new Array('Bayern','Berlin','Hamburg');
    states['Morocco'] = new Array('Casablanca','Doukkala Abda','Guelmin');
    states['United Kingdom'] = new Array('England','Scotland','Wales','Northern Ireland');

    Of course I want to get rid of this long script and get this data from above from mysql database.

    Please let me know if you understand what i say and please help me if you can. I really need to now this.

  6. #6
    Join Date
    Sep 2009
    Posts
    18
    I am searching for this from 2 days. And I didn't find anything. I will provide the final script when it's going to work completely.

    Regards!

  7. #7
    Join Date
    Sep 2009
    Posts
    18
    Help! Please! I would really apreciate any help. I think I am not the only one who wants to find if something like this work.
    What about ajax? I know that ajax can connect to a database but how can i extract that data into states array or the other one.

    Thanks!

  8. #8
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441

    Question More information please ...

    Post a SAMPLE of the related 'country', 'region' and 'city' data entries from your database.

    If I can see a sample, I'll try a solution, but I'm not into starting from scratch.

  9. #9
    Join Date
    Sep 2009
    Posts
    18
    In my database are all the country region and cities and the script I put it here all. All I want is that these array from .js file to be gone and to have arrays that extract data from database. database is selectstates, table is members and then are country,region and city... My first try was to pass php array from query to this new java script array but it didn't work and I delete everything.

    Look for an example here:

    postcrossing(dot)com(slash)signup

    That form extracts all from database in that lists.
    That is what I want but I need to have this javascript function to change the region when the first choice is made and then the to change the third when the second chance is made.

    Thanks a lot for helping me and for response.

  10. #10
    Join Date
    Mar 2009
    Location
    Texas
    Posts
    124
    yes javascript and php can be used together. php to do the database(SERVER) side commands and javascript to the page(CLIENT-SIDE ) commands. Its getting the two to work together that you need to do.

    I'm trying to do the same thing... I have 5 sites that need the same thing. When i get it working i will post...

  11. #11
    Join Date
    Mar 2009
    Location
    Texas
    Posts
    124
    Code:
    <SCRIPT language=JavaScript>
    function reload(form)
    {
    var val=form.state_id.options[form.state_id.options.selectedIndex].value;
    //var cid=form.clubid.value;
    self.location='statetest2.php' + '?state_id=' + val ;
    }
    </script>
    PHP Code:
    if(isset($_GET['state_id'])and strlen($_GET['state_id']) > 0){
        
    $state_id $_GET['state_id'];
        
        echo 
    '<select style="width: 15em" name="state_id" id="state_id" onchange="reload(this.form)">';

                  
    $statesql "SELECT * FROM `ebar_state` ";
                  
    $stateres mysql_query($statesql);
                  if (
    $stateres) {
                    while (
    $state mysql_fetch_assoc($stateres) ) {
                        if (
    $state_id == $state['id']) {
                            echo 
    '<option value="'.$state['id'].'" selected="selected">'.$state['state'].'</option>';
                        } else {
                        echo 
    '<option value="'.$state['id'].'">'.$state['state'].'</option>';
                        }
                     }
                  }
                  echo 
    '</select>';
                  echo 
    '<select style="width: 15em" name="county" id="county">';
                  
    $cquery mysql_query("SELECT * FROM `ebar_county` WHERE `state_id` ='".$state_id."' ORDER BY `county`");
                  if(
    $cquery) {
                      while (
    $co mysql_fetch_assoc($cquery) ) {
                          echo 
    '<option value="'.$co['id'].'">'.$co['county'].'</option>';
                      }
                  } else {
                      echo 
    'umm no.' .mysql_error();
                  }
    } else {
        echo 
    '<select style="width: 15em" name="state_id" id="state_id" onchange="reload(this.form)">';
        
    $statesql "SELECT * FROM `ebar_state` ";
        
    $stateres mysql_query($statesql);
        if (
    $stateres) {
            while (
    $state mysql_fetch_assoc($stateres) ) {
                echo 
    '<option value="'.$state['id'].'">'.$state['state'].'</option>';
            }
        }
        echo 
    '</select>';


  12. #12
    Join Date
    Oct 2009
    Posts
    4
    I think the easiest way to do what you want is to use php to populate the dropdown list when ur page loads up.

    PHP Code:
    // connect to mysql
    // execute your query
    echo "<SELECT id=\"myDropDown\">"
    while ($row mysql_fetch_row($your_query_results) {
      echo 
    "<OPTION>{$row[0]}</OPTION>"
    }
    echo 
    "</SELECT>" 
    and then in your javascript code do the following
    Code:
    var mySelectElement = document.getElementById("myDropDown");
    var myListOfOptions = mySelectElement.getElementsByTagName("OPTION");
    thus you will have a list of all your drop down options that originally came from your database.

    hope this helps

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles