0

I have two select dropdowns on a php form submission page. The first dropdown is basic and shows/hides the second dropdown. The second dropdown is a category/filter list that is populated by a fetch pdo loop. I am trying to auto select the second dropdown(category) based on what the user selects in the first dropdown.

I have tried to populate the second based on the first dropdown, but for these you have to assign a value to be sorted and my dropdown's value (id) is auto populated by the database in a loop and I can't figure out how to get the single value (Echo out values in foreach loop) from each category or how to reference a php value in jquery. (populate second dropdown based on selected value of first dropdown)

Other research i've done: What's the best and easiest way to Populate a dropdown based on another dropdown https://www.daftlogic.com/information-programmatically-preselect-dropdown-using-javascript.htm

This is the last feature I need to develop for this project before I hand it in and I am just learning back-end development - I have been trying to figure this out for a week and have researched and implemented for hours. I would be really grateful to any guidance provided. I am not strong in jquery or javascript.

My database for the categories:

tbl_category
|------------------|
|cat_id | cat_name |
|------------------|
|1      | One      |
|------------------|
|2      | Two      |
|------------------|
|3      | Three    |
|------------------|
|4      | Four     |
|------------------|
|5      | Jeopardy |
|------------------|
|6      | Final    |
|------------------|

my code (admin_addquestion.php):


<?php
require_once 'scripts/config.php';
confirm_logged_in();

$cat_tbl            = 'tbl_category';
$product_categories = getAll($cat_tbl);

if (isset($_POST['submit'])) {
$cat     = $_POST['catList'];

$result  = addQuestion($cat);        
        $message = $result;
    }

?>

<script>

$(function() {
        $('.questionselector').change(function(){
            $('.rounds').hide();
            $('#' + $(this).val()).show();
        });
    });
</script>

<form  action="admin_addquestion.php" method="post" enctype="multipart/form-data" class="md-form">


<Select class="questionselector">
   <option value="none">Select a Question Type</option>

   <option value="one">Round One</option>
   <option value="two">Round Two</option>
   <option value="three">Round Three</option>
   <option value="four">Round Four</option>
   <option value="five">Round Five</option>
   <option value="six">Final Round</option>

</Select>

<select name="catList" id="catlist select" class="mdb-select md-form mb-4 initialized" >
        <option value="" disabled selected>Insert into Category...</option>
        <?php while ($product_category = $product_categories->fetch(PDO::FETCH_ASSOC)): ?>
<option value="<?php echo $product_category['cat_id']; ?>">
    <?php echo $product_category['cat_name']; ?> 
</option>
<?php endwhile; ?>
    </select>

<div id="one" class="rounds" style="display:none">
content
</div>

<div id="two" class="rounds" style="display:none">
content
</div>

<div id="three" class="rounds" style="display:none">
content
</div>

<div id="five" class="rounds" style="display:none">
content
</div>

<div id="six" class="rounds" style="display:none">
content
</div>

<button class="btn btn-outline-info btn-rounded btn-block z-depth-0 my-4 waves-effect" type="submit" name="submit">Submit</button>

</form>

Currently, a user selects a round from the first dropdown (round one, round two, etc) and then they must independently select which category/round to insert the content/questions into from the second dropdown (One, Two, Three, Four, Five, Six, Final). The second dropdown's options are already populated by the database. I would like the user to be able to select a round, and have the second dropdown auto-selected based on their choice from the first select/dropdown. (eg, user selects Round One and then in the second dropdown, One is already chosen for them.)

S Malfoy
  • 23
  • 1
  • 8

2 Answers2

0

if you can change the values of the first select and the ids of your round divs this would be easier. But if you can't you can use a switch statement and assign the numeric value to your catlist select list.

<script>

    $(function() {




            $('.questionselector').change(function(){
                var roundNumber;


                switch($(this).val())
                {
                    case "one":
                         roundNumber = 1;
                         break;
                    case "two":
                         roundNumber = 2;
                         break;
                    case "three":
                         roundNumber = 3;
                         break;
                    case "four":
                         roundNumber = 4;
                         break;
                    case "five":
                         roundNumber = 5;
                         break;
                    case "six":
                         roundNumber = 6;
                         break;
                }


                $('.rounds').hide();
                $('#' + $(this).val()).show();
                $('#catlist').val(roundNumber);
            });
        });
    </script>
Tyddlywink
  • 876
  • 7
  • 28
  • Unfortunately this isn't working. The divs show/hide per usual but the second select does not change based on the first one. There are no errors in the console. Nothing seems to be happening. – S Malfoy Jul 15 '19 at 01:49
  • I capitalized your catlist id in my code change `$('#catList').val(roundNumber)` to `$('#catlist').val(roundNumber)` – Tyddlywink Jul 15 '19 at 02:12
  • Thank you so much, it is working perfectly now. I very much appreciate your help! – S Malfoy Jul 15 '19 at 02:18
0

My answer is a very basic example of how to use an Ajax request to create a second select list.

MAIN.PHP

<script>
 function ajax( id ) {
    var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("new_select").innerHTML =
      this.responseText;
    }
  };
    var url = '/test.php?id='+id;
    if( id ) {  
        xhttp.open("GET", url, true);
        xhttp.send();
    }
 }
</script>
<div>
    <select onchange="ajax( this.value );">
        <option>select something</option>
        <option value="dog">Dog</option>
        <option value="cat">Cat</option>
        <option value="snake">Snake</option>
    </select>
</div>
<div id="new_select">
</div>  

TEST.PHP

<select>
<?php

/* pretend the below arrays came from your database instead */
$array['dog'] = array( "Great Dane", "Labrador", "Husky", "German Shepherd" );
$array['cat'] = array( "Siamese", "Main Coon", "Siberian Shorthair" );
$array['snake'] = array( "Python", "Cobra", "Taipan", "King Brown" );

echo "<option>select something</option>";
foreach( $array[$_GET['id']] as $option ) {
    echo "<option>" . $option . "</option>";
}
?>
</select>

The bit of code here:

onchange="ajax( this.value );

sends the selected value to the ajax request. Which in turn sends it to test.php using GET. From there you can use the GET variable to get the data from your database. This is a very basic ajax example, not fit for a production environment. But it should get you where you need to be.

To see it in action: https://xisse.com/main.php

Erik
  • 384
  • 1
  • 9