0

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:

If the user selects an option in the category dropbox the second select list will show all the options in that category.

<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >                                                                                 
<?php
 while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo 
$rows['Section_Name'];?></option>
<?php   }
             ?>              
    </select> 


 <label>Section</label>
 <select class="form-control selcls" name="txtsection" id="txtsection" >
 <?php
 while ($rows = mysqli_fetch_array($queryResultsec)) {?>
 <option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo 
 $rows['Section_Name'];?></option>   <?php  }
             ?>              
    </select>      
</hmtl> 

3 Answers3

0

Try This Code:

$("#select1").change(function() {
  if ($(this).data('options') === undefined) {
    /*Taking an array of all options-2 and kind of embedding it on the select1*/
    $(this).data('options', $('#select2 option').clone());
  }
  var id = $(this).val();
  var options = $(this).data('options').filter('[value=' + id + ']');
  $('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
      <option value="1">Fruit</option>
      <option value="2">Animal</option>
      <option value="3">Bird</option>
      <option value="4">Car</option>
    </select>


<select name="select2" id="select2">
      <option value="1">Banana</option>
      <option value="1">Apple</option>
      <option value="1">Orange</option>
      <option value="2">Wolf</option>
      <option value="2">Fox</option>
      <option value="2">Bear</option>
      <option value="3">Eagle</option>
      <option value="3">Hawk</option>
      <option value="4">BWM<option>
    </select>
S4NDM4N
  • 904
  • 2
  • 11
  • 26
JavidRathod
  • 483
  • 2
  • 10
  • i try already try this code, I think this only work for static data, what i need is dynamically change base on my database – Jeremy DelaCruz Oct 11 '17 at 05:58
  • You Need to call ajax and get Json data as a response and set HTML of your 2nd select dropdown. – JavidRathod Oct 11 '17 at 06:02
  • you have to share your code here so i can provide better solution – JavidRathod Oct 11 '17 at 06:10
  • i already have my select codes can you please help me thank you sir. – Jeremy DelaCruz Oct 11 '17 at 06:23
  • @javidrathod small advice it's best to wait till the poster shows his / her code so you can give a better answer I'm not saying your answer is wrong but once the poster posts their code the answers posted prior might get invalid. – S4NDM4N Oct 11 '17 at 06:59
0

Do one thing 1-Keep your second dropdown empty. 2-Call jquery ajax to get the first dropdown value on change create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value 3-get the response to ajax method and get the output

0

I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.

Based on that, I created the code below.

This would be your selection area.

<hmtl>
    <head>
        <script   src="https://code.jquery.com/jquery-3.2.1.min.js"   integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="   crossorigin="anonymous"></script>
    </head>
    <body>
        <label>Section</label>
        <select class="form-control selcls" name="txtsection" id="cat" >
            <?php
                while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
                    <option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
            <?php   }   ?>
        </select>
    <label>Section</label>
        <select class="form-control selcls" name="txtsection" id="options" ></select>
    </body>    
</html>

This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.

$(document).ready(function(){
    $(document).on('change', '#cat', function(){
        $.ajax({
            url: 'getOptions.php',
            type: 'get',
            data: {
                catId: $(this).prop('id')
            }
        }).then(function (response) {
            $('#options').html(response);
        });
    });
})

The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.

<?php
include_once('dbconnect.php');

//I'm not a big mysqli user
if(!empty($_GET["id"])){
    $results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
    $results -> bind_param('i', $_GET["id"]);
    $results -> execute();
    $rowNum = $results -> num_rows;

    if ($rowNum > 0){
        while($optRows = $results -> fetch_assoc()){ ?>
            <option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
        <?php
        }
    }
}?>

Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.

As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.

Pang
  • 9,564
  • 146
  • 81
  • 122
S4NDM4N
  • 904
  • 2
  • 11
  • 26
  • Can i ask to the part where you execute the query ? I what to know what meaning of "?" it shoud be the value which you get "$_GET('id') – Jeremy DelaCruz Oct 11 '17 at 10:12
  • Oh the `?` in the query is a place holder for which the value get bound by the `bind_param('i', $_GET["id"])` the `i` in the `bind_param` is the data type stands for integer if it's a character then `s` read on about he prepared statements. Also you should get used to using prepared statements 'cos it's more secure. – S4NDM4N Oct 11 '17 at 10:16
  • I think you have error in the part "var catid = ;" what suppose to be the value of it – Jeremy DelaCruz Oct 11 '17 at 10:28
  • Ah yes a typo while I was writing this sorry about that. – S4NDM4N Oct 11 '17 at 10:29
  • So it just a empty variable? – Jeremy DelaCruz Oct 11 '17 at 10:33
  • I removed it from the code I've assigned the id inside the `AJAX` see this line `data: { catId: $(this).prop('id') }`. I was going to use an `var` for this but realized it's not needed just forgot to delete. – S4NDM4N Oct 11 '17 at 10:36
  • Im sorry If i took lot of your time i just really need some. Can i ask if it really need the " – Jeremy DelaCruz Oct 11 '17 at 10:43
  • It's ok, yeah you need it I updated the code again. What I do there is I use `` till the HTML part close it then write the `options` and re-open the `` in order to close the `while` loop and the other statements. – S4NDM4N Oct 11 '17 at 10:54
  • You really help me to learn deeper about ajax and jquery i really thankful that their are peaple like you much appreciated =) – Jeremy DelaCruz Oct 11 '17 at 11:00
  • NP m8 I was once like you so happy to help some one wanting to learn not just copy paste. – S4NDM4N Oct 11 '17 at 11:01
  • hey bud can you link me some related trend about this solution – Jeremy DelaCruz Oct 11 '17 at 14:31
  • finally i successfully done it thank you very much =) – Jeremy DelaCruz Oct 11 '17 at 15:54
  • @JeremyDelaCruz happy to here you got it to work. I don't know what you mean by "_related trends_" but basically what I've used in my answer is `PHP`, `JavaScript = JQuery and AJAX` with `mysqli_*` which is using prepared statements to bind value variable. Also keep in mind that using prepared statements negate the threat posse by some one trying to attack you sight using [SQL Injection](https://en.wikipedia.org/wiki/SQL_injection). And as references I just use the online manuals of those mentioned languages. – S4NDM4N Oct 12 '17 at 02:52