简体   繁体   中英

Dynamically populate two dropdown menus

I'm not (as I am certain you'll notice below) a programmer or coder. I write network documentation manuals.

That said, I do have some familiarity with HTML, php, css, and so forth. But what follows has stumped me utterly and completely:

I am attempting to build a site for a friend of mine who is in a bind, and though everything else is going fine, I do have to redirect the end-user to a webpage built specifically for their community.

What I need is a way for the end-user to click on a dropdown menu which lists (through a MySQL query) all of the states where records are available, which, upon their selection of an option within the first menu, a second menu is populated by (again by way of MySQL) the communities within that state.

Though I've scoured the internet for things that might be useful, I find that I am simply not well-equipped for the logic of coding. I did find, however, one site that shows a basic version of what I am trying to do ( see here ), but I can't seem to get it to work with MySQL. This is where I am so far:

script --

<script>
 function swapOptions(ArrayName) {
       var ExSelect = document.theForm.sites;
       var theArray = eval(ArrayName);
       setOptionText(ExSelect, theArray);
    }

 function setOptionText(theSelect, theArray) {
       for (loop = 0; loop < theSelect.options.length; loop++) {
           theSelect.options[loop].text = theArray[loop];
       }
    }
 </script>

and HTML --

 <form name="theForm">
   <select name="chooseCat" onchange="swapOptions(this.options[selectedIndex].text);">
        <option value="">Please select your state ...</option>'
                 <?php 
                    $query = mysql_query("SELECT DISTINCT state FROM sites ORDER BY state") 
                           or die(mysql_error());  
                    while ($result = mysql_fetch_assoc($query)) {   
                           $stateChoice = $result['state'];                                      
                             echo '<option value="';
                             echo "$stateChoice"; 
                             echo '">';
                             echo "$stateChoice";  
                             echo '</option>';
                             echo '<br />';                  
                     }
                  ?>
    </select> 
    <select name="sites" style="min-width: 100px;" onchange="location.href='reports.php?page=' + this.options[this.selectedIndex].value;">
                  <?php 
                     $query = mysql_query("SELECT * FROM sites") 
                            or die(mysql_error());  
                     while ($result = mysql_fetch_assoc($query)) {                                      
                            echo '<option value="';
                            echo '">';
                            echo $result['longname'];  
                            echo '</option>';
                            echo '<br />';                  
                      }
                   ?>
     </select>
 </form>

This returns two dropdowns. The first with the results of my query for the states available, listed alphabetically in the dropdown. The second has the long-names of all of the sites listed, but for all of the sites in the table, not just the ones within a certain state (the state just chosen).

In the end, dropdown 1 should be populated with all of the available states. Once the user selects their state, this should trigger the population of dropdown 2 with all of the communities within their chosen state. Once the choice of community is clicked in dropdown 2, it should redirect the user's browser to, for example, http://www.webpage.com/reports.php?page=communityNameGoesHere ...

Thanks so much for any advice you might have here :)

You have a couple of routes you can go. You can use AJAX to grab the values for the sites list upon selection of the state. Or, you could simply use javascript to filter the values in the second list based on the selection of the state.

I might think the second would be a better option for you since it is more straight forward. So I will focus on that, but if you want an AJAX solution that can be discussed as well.

I would revise your script to make a single DB call. Since you are querying the information from one table, there is no reason to call the DB twice.

Simply use SELECT * FROM sites ORDER BY states ASC

You can then loop through the result sets and do something like this

$array = array();
while ($row = mysql_fetch_assoc($query)) {
    $array[$row['state']][] = $row;
}

Then build your first select and populate the options with:

foreach($array as $state => $not_used) {
    echo sprintf('<option value="%1$s">%1$s</option><br />', $state);
}

Now build the second select and populate the options with:

foreach($array as $state => $state_array) {
    foreach($state_array as $site) {
        echo sprintf('<option class="%1$s" value="%2$s">%3$s</option><br />', $state, $site['shortname'], $site['longname']);
    }
}

Note, I have added a HTML class property here. This makes a convenient handle to show only those items you want to show.

You give the sites select element an ID of sites , and the states selected element an id of states . Set following rules in your CSS:

#sites { display: none; }
#sites option { display: none; }

This will initially hide the sites menu and all the options within it.

I will now show some simple jQuery for hiding/showing the proper elements, and for making the redirection upon site selection. I mention jQuery as this makes what you are trying to do a snap.

$(document).ready(function () { // calls this function on document ready
    $('#states').change(function() { // binds onchange function to #states select
        var selected_state = $(this).val(); // gets current selected value of #states select
        $('#sites option').hide(); // hides all options in sites select
        $('.'+selected_state).show(); // show site options with class = selected_state
        $('#sites').show(); // show entire #sites select (only useful for display from initial hidden state)
    });
    $('#sites').change(function() { // binds onchange function to #sites select
        window.location = 'reports.php?page=' + $(this).val(); // perform redirect
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM