javascriptphpjquerydrop-down-menuauto-populate

How to keep jQuery auto populated dropdown result selected?


I have this dynamic dropdown which fetches result on selection of one select menu, but the challenge I am facing after it auto populates the results on the second dropdown on submit of form the value of second select disappears. How to make it not disappear even after submit?

Here is my HTML & PHP

 <div class="row form-group">
                    <div class="col-md-12">
                    <label class="sr-only" for="job_category">Select Job Category</label>
            <select name="job_category" id="category" class='form-control'>
            <option value='' selected='selected' disabled='disabled'>Select Job Category</option>
            <?php           
            $sql="select * from job_category ";             
            foreach ($db->query($sql) as $row) {
            ?>
            <option value='<?php echo $row[cat_id]; ?>' <?php if($job_category == ''.$row[cat_id].'') echo 'selected="selected"'; ?>><?php echo $row[cat_name]; ?></option>
            <?php   
            }
            ?>          
            </select>
            </div>
        </div>

                <div class='row form-group'>
                    <div class='col-md-12'>
                    <label class='sr-only' for='job_subcategory'>Select Job Industry</label>
                <select name='job_subcategory' id='sub-category' class='form-control'>
                <option value='' selected='selected' disabled='disabled'>Select Job Industry</option>
                </select>
                </div>
            </div>  

Here is my JQ

$(document).ready(function() {
    $('#category').change(function(){
        var cat_id=$('#category').val();
        $('#sub-category').empty(); 
        $.get('fetchCategories.php',{'cat_id':cat_id},function(return_data){            
        $.each(return_data.data, function(key,value){
                $("#sub-category").append("<option value='" + value.subcat_id +"'>"+value.subcat_name+"</option>");
            });

        }, "json");
        });
    });

And my fetchCategories.php

@$cat_id=$_GET['cat_id'];
//$cat_id=2;
/// Preventing injection attack //// 
if(!is_numeric($cat_id)){
echo "Data Error";
exit;
 }
/// end of checking injection attack ////
require "includes/config.php";

$sql="select subcat_name,subcat_id from job_subcategory where cat_id='$cat_id'";
$row=$db->prepare($sql);
$row->execute();
$result=$row->fetchAll(PDO::FETCH_ASSOC);

$main = array('data'=>$result);
echo json_encode($main);

Solution

  • You can use localStorage to store the current value which is selected by user on change of select-box and then when your page gets reload just fetch the stored data from localStorage and then call your ajax to retrieve required data.

    Your jquery code will somewhat look like below (Sorry for any syntax error) :

    $(document).ready(function() {
      //check if there is any value in localStorage
      if (localStorage.getItem("save") != null) {
        //get that value
        var value = localStorage.getItem("save");
        console.log(value);
        //set value in selected box
        $("#sub-category").val(value);
      }
      //onchange of subcategory
      $('#sub-category').change(function() {
        var values = $(this).val();
        localStorage.clear(); //clear previous data
        localStorage.setItem("save", values); //add data to storage
    
      });
    
    
      $('#category').change(function() {
        var cat_id = $('#category').val();
        $('#sub-category').empty();
        $.get('fetchCategories.php', {
          'cat_id': cat_id
        }, function(return_data) {
          $.each(return_data.data, function(key, value) {
            $("#sub-category").append("<option value='" + value.subcat_id + "'>" + value.subcat_name + "</option>");
          });
    
        }, "json");
      });
    
    });