简体   繁体   中英

How to change a select option based on choosing other select option

I have two select options one is the category and the second is subcategory which I fetched the first select options from MySQL and now I want to fetch the subcategories based on the selected category by using a query.

like select cat_name form DB1 where id= ID_OF_SELECTED CATEGORY

                    <div class="form-group">
                    <label style="align-content:center" for="inputdefault">Select a category</label>                    
                    <?php
                    $sql = "SELECT * from noorizone.categories where parent=''";
                    $result = $con->query($sql);
                    // output data of each row
                    echo "<select class='form-control' id='sel1' onchange='getSubCategory()'>";
                    while($row = mysqli_fetch_array($result)) 
                    {
                        echo "<option value=".$row["id"].">".$row["name"]."</option>" ;
                    }
                    $maincat= $row["id"];
                    echo "</select>"
                    ?>  
                </div>

That is the code which i have fetched the values for main category. I know that its possible using AJAX request but i have no idea about ajax.

在此处输入图片说明

Can you please help me out with my problem.

Here is an algorithm on how to achieve this:

  1. Using Javascript/Jquery, listen for change in value of "Category" dropdown options.
  2. Grab that value and using AJAX send it to your controller->model (If you are using MVC pattern).
  3. Based on this value do a sql query and get the required "Sub Category options" for that parent Category option and return the value.
  4. Get these returned values and populate the "Sub Category" options dropdown.

Here is pseudo code:

//Category Dropdown
<select name="status" id="status">
  <option value="1">Active</option>
  <option value="0">Inactive</option>
</select>

JS:

$("#status").change(function(){
  var status = this.value;

  $.ajax({
    url: 'call_your_controller_function',
  success: function(response){
    var data = response;    //Response should be array like option1 , option2, option3
    var option = '';
    for (var i=0;i<data.length;i++){
       option += '<option value="'+ data[i] + '">' + data[i] + '</option>';
    }
    //Now populate the second dropdown i.e "Sub Category"
    $('#id_of_sub_category').append(option);
  },
  error: function(){
    alert('failure');
   }
 });

});

This is bit complex than you expected. But I'm using the same logic/ technology.

var tagSearch = function( _opts ){
        var search = {};
    search.data = new Array();
    search.errors = new Array();

    /* defaults */
    search.opts = {
        tagsRootObject:"tags",
      jsonEndPoint:"/echo/json/",
      inputSelector:'input'
    };

    $.extend( true, search.opts, _opts );

    /* get terms from external source */
    search.getTerms = function(){

        dfd = $.Deferred();
        $.ajax({
          type: "GET",
          dataType: "json",
          url: search.opts.jsonEndPoint,
          success: function ( data ) {

            if( data.hasOwnProperty('success') && data.success === true ){
               dfd.resolve( data );

                        }  
          },
          error: function(jqXHR, textStatus, errorThrown){
              console.log('Ajax Status', textStatus);
              return false;
          }
        });
       return dfd.promise();
    }();

    search.setTerms = function( $form, data ){
        var terms = null, 
            term, $checkbox, $label, $fieldset;

        if( data.hasOwnProperty( search.opts.tagsRootObject ) ){
            terms = data[ search.opts.tagsRootObject ];

          $fieldset = $('<fieldset>');

          if( Object.keys( terms ).length > 0 ){
            $form.append( $fieldset ); 
          }

          for( var t in terms ){
           term = terms[ t ];
           $checkbox = $('<input>')
                                  .attr({
                                    id:'term_' + t,
                                    class:'__term',
                                    type:'checkbox'
                                  })
                                  .data('id', t );

           $checkbox.appendTo( $fieldset );
           $label = $("<label>")
                                .text( t ) // object key will be the label
                                            .attr({for:'term_'+ t })
                                            .insertAfter( $checkbox );
             /* setting up new titles */
             if( search.opts.tags.hasOwnProperty( t ) ){
               $label.text( search.opts.tags[ t ].label );
             }
          }

                }else{
            search.errors.push("Unable to find search terms");
              }
    };

    $.widget( "custom.catTags", $.ui.autocomplete, {
      _create: function() {
        this._super();
        this.widget().menu( "option", "items", "> :not(.ui-autocomplete-category)" );
      },
      _renderMenu: function( ul, items ) {
        var that = this,
          currentCategory = "";
        $.each( items, function( index, item ) {
          var li;
          if ( item.category != currentCategory ) {
            ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
            currentCategory = item.category;
          }
          li = that._renderItemData( ul, item );
          if ( item.category ) {
            li.attr( "aria-label", item.category + " : " + item.label );
          }
        });
      }
    });

    search.run = function( config ){
        config.ele.catTags( config.settings );
        //config.ele.catTags( $.extend( config.settings, {source: search.data} ) );
    };

    $.when( search.getTerms ).done(function ( terms ) {

      /* if something needed from the beginning */
      search.data = [
        { label: "Default value 1", category: "" },
        { label: "Default value 2", category: "" },
        { label: "Something", category: "" }
      ];

      $( function() {
                var $form, termsObj = {};

            termsObj.enabled = new Array();

            $form = $( search.opts.formSelector );

                        search.setTerms( $form, terms );

            /* Binding term checkboxes */
            $form.on('click', '.__term', function(){
                var $this = $(this),
                    termId, isChecked, termIndex;


              search.data.length = 0;

              termId =  $this.data('id');
              isChecked =  $this.is(':checked');

              if( isChecked ){

                termsObj.enabled[ termId ] = terms.records[ termId ];

              }else{
                if( termsObj.enabled.hasOwnProperty( termId ) ){
                        delete termsObj.enabled[ termId ];
                }
              }

                    for( var prop in termsObj.enabled ){
                var currentTerm, record, label;

                    currentTerm = termsObj.enabled[ prop ];

                        if( currentTerm instanceof Array ){
                                                currentTerm.map( function( obj ) {

                          label = ( search.opts.tags.hasOwnProperty(prop) ) ? search.opts.tags[ prop ].label  : prop;
                          record = {
                            label: obj,
                            category: label
                         };

                          search.data.push( record );
                        });

                                        }
                            } 

            }); 

                        search.run({
                ele: $form.find( search.opts.inputSelector ),
                settings:{
                  delay: 0,
                  source: search.data
                }
            });
      });

    });

    if( search.errors.length > 0 ){
      console.log("Errors:", search.errors );
    }

}({
  jsonEndPoint:'/gh/get/response.json/dkarandana/pub_response/tree/master/AutoCompleteDemo/',
    tagsRootObject:'records',
  formSelector:'form',
  inputSelector:'#search',
    tags:{
    technology:{
        label:"Technology"
    },
    model:{
        label:"Model / Series"
    },
    manufacturer:{
        label:"Manufacturer"
    },
    pdf:{
        label:"PDF",
      autocomplete:false
    }
  }
});

Here i got the answer. Script file :

 <script type="text/javascript"> $(document).ready(function(){ $('#maincategory').on('change',function(){ var mainactegory_ID = $(this).val(); if(mainactegory_ID){ $.ajax({ type:'POST', url:'ajaxData.php', data:'mainactegory_ID='+mainactegory_ID, success:function(html){ $('#subcat1').html(html); $('#subcat2').html('<option value="">Select sub 1</option>'); } }); }else{ $('#subcat1').html('<option value="">Select main cat</option>'); $('#city').html('<option value="">Select sub cat 1</option>'); } }); $('#subcat1').on('change',function(){ var subcat1_id = $(this).val(); if(subcat1_id){ $.ajax({ type:'POST', url:'ajaxData.php', data:'subcat1_id='+subcat1_id, success:function(html){ $('#city').html(html); } }); }else{ $('#city').html('<option value="">select sub 1</option>'); } }); }); </script> 
  <div class="form-group"> <label style="align-content:center" for="inputdefault">Select a category</label> <?php $maincategory= "select * from noorizone.categories where parent=''"; $result2= $con->query($maincategory); ?> <select class= "form-control" name="maincategory" id="maincategory"> <option value='0' > Select category</option> <?php while($row = mysqli_fetch_array($result2)) echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'; ?> </select> </div> <div class="form-group"> <label style="align-content:center" for="inputdefault">Sub category 1</label> <select class="form-control" name="subcat1" id="subcat1"> </select> </div> <div class="form-group"> <label style="align-content:center" for="inputdefault">Sub category 1</label> <select class="form-control" name="city" id="city"> </select> </div> 

 <?php //Include database configuration file //Include database configuration file $db = mysqli_connect("localhost:3306","root","mysqlpassword"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_select_db($db,"mydb1"); if(isset($_POST["mainactegory_ID"]) && !empty($_POST["mainactegory_ID"])){ //Get all state data $query = $db->query("select * from noorizone.categories where parent = ".$_POST['mainactegory_ID']); //Count total number of rows $rowCount = $query->num_rows; //Display states list if($rowCount > 0){ echo '<option value="">sub cat..</option>'; while($row = $query->fetch_assoc()){ echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'; } }else{ echo '<option value="">sub1 not available</option>'; } } if(isset($_POST["subcat1_id"]) && !empty($_POST["subcat1_id"])){ //Get all city data $query = $db->query("select * from noorizone.categories where parent = ".$_POST['subcat1_id']); //Count total number of rows $rowCount = $query->num_rows; //Display cities list if($rowCount > 0){ echo '<option value="">Select sub cat 2 </option>'; while($row = $query->fetch_assoc()){ echo '<option value="'.$row['id'].'">'.$row['name'].'</option>'; } }else{ echo '<option value="">category not available</option>'; } } ?> 

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