最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change a select option based on choosing other select option - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Nov 6, 2017 at 12:09 fdomn-m 28.6k8 gold badges39 silver badges67 bronze badges asked Nov 6, 2017 at 12:02 zainudin noorizainudin noori 1914 silver badges12 bronze badges 8
  • 1 Take Courses about ajax no one will write code for you – Mohammad hayajneh Commented Nov 6, 2017 at 12:05
  • jquery's ajax API is pretty simple to understand: api.jquery./jquery.ajax – Zander Commented Nov 6, 2017 at 12:06
  • Are you able to use jQuery which has easy ajax handling and DOM updating that you could use to change the options of your second input object. You'll need a php page that takes the category as input (eg in $_GET[] ) and returns a block of HTML for your selector's options that you can switch in using jquery or innerHtml of the selector. – Matt_S Commented Nov 6, 2017 at 12:07
  • I Suggest taking a look at this tutorial ,it solves the same probelm you have: codexworld./… Good Luck! – Cosmin_Victor Commented Nov 6, 2017 at 12:09
  • you can get help from here: stackoverflow./questions/42524122/… here you will get your answer – jasneet bhatia Commented Nov 6, 2017 at 12:14
 |  Show 3 more ments

3 Answers 3

Reset to default 6

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 plex 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.autoplete, {
      _create: function() {
        this._super();
        this.widget().menu( "option", "items", "> :not(.ui-autoplete-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-autoplete-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",
      autoplete: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>';
    }
}
?>

发布评论

评论列表(0)

  1. 暂无评论