如何根据选择其他选择选项更改选择选项

时间:2017-11-06 12:02:11

标签: javascript php jquery html ajax

我有两个选择选项,一个是类别,第二个是子类别,我从MySQL获取了第一个选择选项,现在我想通过使用查询根据所选类别获取子类别。

喜欢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>

这是我获取主类别值的代码。 我知道它可能使用AJAX请求,但我不知道ajax。

enter image description here

请你帮我解决我的问题。

3 个答案:

答案 0 :(得分:6)

以下是如何实现此目的的算法:

  1. 使用Javascript / Jquery,监听“类别”下拉选项值的变化。
  2. 获取该值并使用AJAX将其发送到您的controller-&gt;模型(如果您使用的是MVC模式)。
  3. 根据此值执行sql查询并获取该父类别选项所需的“子类别选项”并返回该值。
  4. 获取这些返回值并填充“子类别”选项下拉列表。
  5. 这是伪代码:

    //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');
       }
     });
    
    });
    

答案 1 :(得分:1)

这比你想象的要复杂一点。但我使用相同的逻辑/技术。

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
    }
  }
});

答案 2 :(得分:0)

我在这里得到了答案。 脚本文件:

&#13;
&#13;
<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>
&#13;
					<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>
&#13;
&#13;
&#13;

&#13;
&#13;
<?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>';
    }
}
?>
&#13;
&#13;
&#13;