Jump to content

Recommended Posts

Dear Team,

I am adding table row in dynamically and in that row i having 4 drop down list called Brand, Category, Sub-Category and model. I want the dropdown list to be populated from databse based on selection of another one ( Brand --> category --> Sub-Category --> model).

My php page is 

image.thumb.png.38ddf699f5c146e5f74ddb54b346a49a.png

My databse is 

image.png.49613308b676b25d9140ec8a67d91c38.pngimage.thumb.png.010a73f710d381548a5a46d6f4c87a05.png

 

My php code is 

<?php

session_start();
error_reporting(0);
ini_set('display_errors','Off');
include("../connection.php");
include("../paginator.class.php");

$id=$_SESSION['id'];

if($_SESSION['id'] == '') {
    session_destroy();
    // header("location:logout.php"); //redirect to index.php
}

$query=mysqli_query($conn,"SELECT * FROM users where id='$id'");
$row=mysqli_fetch_array($query);
$Name = $row['Name'];
$Emp_No = $row['Emp_No'];
$Designation = $row['Designation'];
$Type = $row['User_Type'];
$Type1 = $row['User_Type'];
$Branch = $row['Branch'];
$Approver = $row['Approver'];

?>



<!DOCTYPE html>
<!-- Created by CodingLab |www.youtube.com/CodingLabYT-->
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <!--<title> Drop Down Sidebar Menu | CodingLab </title>-->
    <link rel="stylesheet" href="css/tiv.css">
    <!-- Boxiocns CDN Link -->
    <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

      <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

   </head>
<body>
  <div class="sidebar">
    <div class="logo-details">
        <img src="Image/Schwing_Logo.jpg" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
        <img src="Image/XCMG_LOGO.png" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
    </div>
    <ul class="nav-links">
      <li>
        <a href="Dashboard.php" >
            <i class='bx bxs-dashboard'></i>
          <span class="link_name">Dashboard</span>
        </a>
      </li>
        <li>
            <a href="TIV.php" class="active">
                <i class='bx bx-trending-up'></i>
                <span class="link_name">TIV Sales Data</span>
            </a>
        </li>
        <li>
            <a href="Marketing.php">
                <i class='bx bxs-business'></i>
                <span class="link_name">Marketing & Promotion</span>
            </a>
        </li>
        <li>
            <a href="PartsandService.php">
                <i class='bx bxs-wrench'></i>
                <span class="link_name">Parts & Service</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bxs-user-detail'></i>
                <span class="link_name">Manpower</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bx-book'></i>
                <span class="link_name">Equipement & Population</span>
            </a>
        </li>
      <li>
        <div class="iocn-link">
          <a href="#">
              <i class='bx bx-wallet-alt'></i>
            <span class="link_name">Expenses</span>
          </a>
          <i class='bx bxs-chevron-down arrow' ></i>
        </div>
        <ul class="sub-menu">
          <li><a href="Employee_Expense.php">Employee Expense</a></li>
          <li><a href="Infrastructural_Expense.php">Infrastructural Expense</a></li>
          <li><a href="Other_Expense.php">Other Expense</a></li>
        </ul>
      </li>      
      <li>
        <a href="#">
            <i class='bx bxs-report'></i>
          <span class="link_name">Reports</span>
        </a>
      </li>
     
      <li>
    <div class="profile-details">
      <div class="profile-content">
        <!--<img src="image/profile.jpg" alt="profileImg">-->
      </div>
      <div class="name-job">
        <div class="profile_name"><?php echo $Name; ?></div>
        <div class="job"><?php echo $Designation; ?></div>
      </div>
        <a href="Logout.php">
            <i class='bx bx-log-out'></i>
        </a>
      
    </div>
  </li>
</ul>
  </div>
  <section class="home-section">
      <nav>
          <div class="home-content" style="margin-top:15px">
              <span class="text">TIV Sales Data</span>
          </div>  
      </nav>
          <br />
          <!-- Body Content-->
      <div class="main" style="top:50px;bottom:20px">

          <div>             

                <form method="POST" action="">
                   <p>Select Month: <input type="month" name="month" placeholder="Select Month" required style="width:auto;border:solid; border-color:black;font-family:Cambria;border-radius:5px;height:30px" /> </p>
 

                    <table class="table">
                        <tr>
                            <th style="width:50px">#</th>
                            <th>District</th>
                            <th>Brand</th>
                            <th>Category</th>
                            <th>Sub Category</th>
                            <th>Model</th>
                            <th style="width:80px">Quantity</th>
                            <th>Average Selling Price</th>
                        </tr>
                        <tbody id="tbody">
                            <template id="row-template">
                                  <tr style="text-align: center">
                                        <td></td>
                                      <td>
                                            <select class="background" name="District[]">
                                                  <option value="">District</option>
                                                  <?php
                                                  $qry    =   mysqli_query($conn,"SELECT DISTINCT Brand_Name FROM model ORDER BY Brand_Name ASC");
                                                  while($row = $qry->fetch_assoc()) {
                                                      echo "<option";
                                                      if(isset($_REQUEST['Brand']) and $_REQUEST['Brand']==$row['Brand_Name']) echo ' selected="selected"';
                                                      echo ">{$row['Brand_Name']}</option>\n";
                                                  }
                                                  ?>
                                            </select>
                                        </td>
                                        <td>
                                            <select id="Brand" name="Brand[]">
                                            <option value="">Select Brand</option>
                                            <?php 
                                            $query = "SELECT * FROM brand ORDER BY Brand_Name ASC"; 
                                            $result = $conn->query($query); 
                                            if($result->num_rows > 0){ 
                                                while($row = $result->fetch_assoc()){  
                                                    echo '<option value="'.$row['Brand_ID'].'">'.$row['Brand_Name'].'</option>'; 
                                                } 
                                            }else{ 
                                                echo '<option value="">Country not available</option>'; 
                                            } 
                                            ?>
                                        </select>
                                        </td>
                                      <td>
                                            <select id="Category" name="Category[]">
                                                  <option value="">Select Brand first</option>
                                            </select>
                                        </td>
                                      <td>
                                            <select id="Sub_Category" name="Sub_Category[]" >
                                                  <option value="">Select Category first</option>
                                            </select>
                                        </td>                                     

                                      <td>
                                            <select  id="Model" name="Model[]">
                                                  <option value="">Select Sub-Category first</option>
                                            </select>
                                        </td>
                                        <td><input type='number' name="Quantity[]"></td>
                                        <td><input type='number' name="ASP[]"></td>
                                      <td hidden align='center' style="width:10%">
                                    <input type="checkbox" checked="checked" class="checkbox" name='lang[]' value="<?php echo $ID; ?>" />
                                </td>
                                  </tr>
                                </template>
                        </tbody>
                    </table>

                    <div style="text-align:center">
                        <button type="button" onclick="addItem();" style="font-family:Cambria;float:left;background: #0A2558;color:white;cursor:pointer; height:30px; border-radius:5px; padding:5px">Add New<i class='bx bx-plus-medical' style="margin-left:10px"></i></button>
                        <input type="submit" name="addInvoice" value="Submit" style="width:100px;background: #0A2558; color:white;font-family:Cambria;border-radius:5px;height:30px;" />
                    </div>
                </form>

               <?php
               if (isset($_POST["addInvoice"]))
               {
                   $month = $_POST["month"];
                   $Dealername = $Name;

                   $newDate = date("M-Y", strtotime($month));

                   //for ($a = 0; $a < count($_POST["lang"]); $a++)
                   foreach($_POST['lang'] as $ID => $VAL){
                       $Brand = $_POST['Brand'] [$ID];
                       $Category = $_POST['Category'] [$ID];
                       $Sub_Category = $_POST['Sub_Category'] [$ID];
                       $Model = $_POST['Model'] [$ID];
                       $Quantity = $_POST['Quantity'] [$ID];
                       $ASP = $_POST['ASP'] [$ID];
                       $District = $_POST['District'] [$ID];

                       $sql = "INSERT INTO tiv (Month, Brand, Category, Sub_Category, Model, Quantity, Dealer_Name, District, ASP) VALUES ('$newDate', '$Brand', '$Category', '$Sub_Category', '$Model', '$Quantity', '$Dealername', '$District', '$ASP')";
                       mysqli_query($conn, $sql);
                   }
               }
               ?>

                <script>
	                        const template=document.getElementById('row-template');
                            const tbody=document.getElementById('tbody');
                            let itemCount=0;
  
                            function addItem(){
  	                            const newRow = template.content.cloneNode(true);
                                const firstTd = newRow.querySelector('td:first-child');
                                firstTd.textContent=++itemCount;
                                tbody.appendChild(newRow);
                            }
                </script>
            </div>
          
      </div>
</section>

     <script>
$(document).ready(function(){
    $('#Brand').on('change', function(){
        var BrandID = $(this).val();
        if(BrandID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'Brand_ID='+BrandID,
                success:function(html){
                    $('#Category').html(html);
                    $('#Sub_Category').html('<option value="">Select Category first</option>');
                    $('#Model').html('<option value="">Select Sub_Category first</option>'); 
                }
            }); 
        }else{
           $('#Category').html('<option value="">Select Brand first</option>');
                    $('#Sub_Category').html('<option value="">Select Category first</option>');
                    $('#Model').html('<option value="">Select Sub_Category first</option>'); 
        }
    });
    
    $('#Category').on('change', function(){
        var CategoryID = $(this).val();
        if(CategoryID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'Category_ID='+CategoryID,
                success:function(html){
                    $('#Category').html(html);
                }
            }); 
        }else{
            $('#Category').html('<option value="">Select Model first</option>'); 
        }
    });

    $('#Sub_Category').on('change', function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#Sub_Category').html(html);
                }
            }); 
        }else{
            $('#Sub_Category').html('<option value="">Select Category first</option>'); 
        }
    });

    $('#Model').on('change', function(){
        var stateID = $(this).val();
        if(stateID){
            $.ajax({
                type:'POST',
                url:'ajaxData.php',
                data:'state_id='+stateID,
                success:function(html){
                    $('#Model').html(html);
                }
            }); 
        }else{
            $('#Model').html('<option value="">Select Sub_Category first</option>'); 
        }
    });
});
</script>

        <script>
                function Category_click_click(){
                value_select = $("#Category_click").val();
                $.post('TIV.php',{"Category_click":value_select},function(data){
                })
                }
        </script>

        <script>
                function Sub_Category_click(){
                value_select = $("#Sub_Category").val();
                $.post('TIV.php',{"Sub_Category":value_select},function(data){
                })
                }
        </script>

    <script>
          let arrow = document.querySelectorAll(".arrow");
          for (var i = 0; i < arrow.length; i++) {
            arrow[i].addEventListener("click", (e)=>{
           let arrowParent = e.target.parentElement.parentElement;//selecting main parent of arrow
           arrowParent.classList.toggle("showMenu");
            });
          }
          let sidebar = document.querySelector(".sidebar");
          let sidebarBtn = document.querySelector(".bx-menu");
          console.log(sidebarBtn);
          sidebarBtn.addEventListener("click", ()=>{
            sidebar.classList.toggle("close");
          });
    </script>
</body>
</html>

 

And ajaxData.php code is 

<?php
// Include the database config file
include("../connection.php");

if(!empty($_POST["Brand_ID"])){
    // Fetch state data based on the specific country
    $query = "SELECT * FROM model WHERE Brand_ID = ".$_POST['Brand_ID']." ";
    $result = $conn->query($query);

    // Generate HTML of state options list
    if($result->num_rows > 0){
        echo '<option value="">Select Category</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Category_ID'].'">'.$row['Category_Name'].'</option>';
        }
    }else{
        echo '<option value="">Category not available</option>';
    }
}elseif(!empty($_POST["Category_ID"])){
    // Fetch city data based on the specific state
    $query = "SELECT * FROM model WHERE Sub_Category_ID = ".$_POST['Category_ID']." ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Sub-Category</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Sub_Category_ID'].'">'.$row['Sub_Category_Name'].'</option>';
        }
    }else{
        echo '<option value="">Sub-Category available</option>';
    }
}elseif(!empty($_POST["Sub_Category_ID"])){
    // Fetch city data based on the specific state
    $query = "SELECT * FROM model WHERE Model_ID = ".$_POST['Sub_Category_ID']." ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Model</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Model_ID'].'">'.$row['Model_Name'].'</option>';
        }
    }else{
        echo '<option value="">Model available</option>';
    }
}
?>

Once i crete the new row, the bran list is populating. But if i select the Brand, the other lis is not populating. It is not calling the script and ajax function.

I have attached my bot the file here for your reference.

 

Can any one help me to correct the mistake 

 

ajaxData.txt TIV.txt

there are two reason this is not working - 1) ids must be unique. you cannot use id="Brand" more than once on a page, and 2) the dynamically added elements don't exist when you are attaching the on change event handler (even if you change the selector to be a class name.) you must attach the on change event handler to an element that exists at the time (document is the easiest, though not the most efficient), that will contain the elements you want the event handler to fire for.

assuming you change id='Brand' to class='Brand', the following will attach the on change event handler to all instances of the <select class="Brand" ... within the html document -

$(document).on('change', '.Brand', function(){

since ids must be unique, all the rest of the code manipulating the DOM must be changed so that they don't rely on ids. the way to do this is give the <tr a class name that you can search for, such as 'parent-container', you can then find the current parent container using - 

var parent = $(this).closest('.parent-container');

you can then find and reference the elements within the parent container, by a class name, such as -

parent.find('.Category').html(html);

 

Hi,

Thanks for your reply.

I have modified my code ans per your suggesion. My modified cose is 

 <tr style="text-align: center" class="parent-container">
                                        <td></td>
                                      <td>
                                            <select class="background" name="District[]">
                                                  <option value="">District</option>                                                 
                                            </select>
                                        </td>
                                        <td>
                                            <select id="Brand" name="Brand[]" class="Brand">
                                            <option value="">Select Brand</option>
                                            <?php 
                                            $query = "SELECT * FROM brand ORDER BY Brand_Name ASC"; 
                                            $result = $conn->query($query); 
                                            if($result->num_rows > 0){ 
                                                while($row = $result->fetch_assoc()){  
                                                    echo '<option value="'.$row['Brand_ID'].'">'.$row['Brand_Name'].'</option>'; 
                                                } 
                                            }else{ 
                                                echo '<option value="">Country not available</option>'; 
                                            } 
                                            ?>
                                        </select>
                                        </td>
                                      <td>
                                            <select id="Category" name="Category[]" class="Category">
                                                  <option value="">Select Brand first</option>
                                            </select>
                                        </td>
                                      <td>
                                            <select id="Sub_Category" name="Sub_Category[]" class="Sub_Category">
                                                  <option value="">Select Category first</option>
                                            </select>
                                        </td>                                     

                                      <td>
                                            <select  id="Model" name="Model[]" class="Model">
                                                  <option value="">Select Sub-Category first</option>
                                            </select>
                                        </td>
                                        <td><input type='number' name="Quantity[]"></td>
                                        <td><input type='number' name="ASP[]"></td>
                                      <td hidden align='center' style="width:10%">
                                    <input type="checkbox" checked="checked" class="checkbox" name='lang[]' value="<?php echo $ID; ?>" />
                                </td>
                                  </tr>

 

<script>
            $(document).on('change', '.Brand', function(){
                var BrandID = $(this).val();
                if(BrandID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Brand_ID='+BrandID,
                        success: function (html) {
                            $('#Category').html(html);
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#Category').html('<option value="">Select Brand first</option>');
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.Category', function(){
                var CategoryID = $(this).val();
                if(CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Category_ID='+CategoryID,
                        success: function (html) {
                            $('#Sub_Category').html(html);
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.Sub_Category', function(){
                var Sub_CategoryID = $(this).val();
                if(Sub_CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Sub_Category_ID='+Sub_CategoryID,
                        success: function (html) {
                            $('#Model').html(html);
                        }
                    }); 
                } else {
                            BrandID.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });
    
        </script>

 

When i am selecting Brand it is working (Category list is populating). But wheni am selecting Category again this is not working and Sub-Category list is not pupulating.

 

Can you please lookon it

I turned ON the error reporting. But it is not sohwing any error.

 

Also When i am selecting Brand it is working (Category list is populating) on first row only. If i add more rows, the category list is not populating on the newly added row. It is populating the list on fir row only even if is change the brand on 2nd row.

 

Please help me

What do you mean 'no result'?   What did the debugging show you?  Display what is happening and see why it is not doing what you want.

And no - I don't understand your code so you will have to do this yourself.  As a good programmer would do.

your browser's developer tools console tab may contain errors that would help you find the problem.

the OP only half did the first item i listed (added a class, rather than changing the id to a class), leaving duplicate ids in the dynamically added fields. the second item i listed was done. all the rest of the information i listed was ignored.

 

Why do you have arrays as the names of your select tags?  You didn't specify multiple selections so why an array?

Why do you have id and class attributes?

Why are you 'styling' a tr tag to center text?

And why are you not showing the code that you have modified so we can keep up with you?

My modified code is 

 

<?php

session_start();
//error_reporting(0);
error_reporting(E_ALL);

ini_set('display_errors', '1');
//ini_set('display_errors','Off');
include("../connection.php");
include("../paginator.class.php");

$id=$_SESSION['id'];

if($_SESSION['id'] == '') {
    session_destroy();
    // header("location:logout.php"); //redirect to index.php
}

$query=mysqli_query($conn,"SELECT * FROM users where id='$id'");
$row=mysqli_fetch_array($query);
$Name = $row['Name'];
$Emp_No = $row['Emp_No'];
$Designation = $row['Designation'];
$Type = $row['User_Type'];
$Type1 = $row['User_Type'];
$Branch = $row['Branch'];
$Approver = $row['Approver'];

?>



<!DOCTYPE html>
<!-- Created by CodingLab |www.youtube.com/CodingLabYT-->
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <!--<title> Drop Down Sidebar Menu | CodingLab </title>-->
    <link rel="stylesheet" href="css/tiv.css">
    <!-- Boxiocns CDN Link -->
    <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

      <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

   </head>
<body>
  <div class="sidebar">
    <div class="logo-details">
        <img src="Image/Schwing_Logo.jpg" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
        <img src="Image/XCMG_LOGO.png" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
    </div>
    <ul class="nav-links">
      <li>
        <a href="Dashboard.php" >
            <i class='bx bxs-dashboard'></i>
          <span class="link_name">Dashboard</span>
        </a>
      </li>
        <li>
            <a href="TIV.php" class="active">
                <i class='bx bx-trending-up'></i>
                <span class="link_name">TIV Sales Data</span>
            </a>
        </li>
        <li>
            <a href="Marketing.php">
                <i class='bx bxs-business'></i>
                <span class="link_name">Marketing & Promotion</span>
            </a>
        </li>
        <li>
            <a href="PartsandService.php">
                <i class='bx bxs-wrench'></i>
                <span class="link_name">Parts & Service</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bxs-user-detail'></i>
                <span class="link_name">Manpower</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bx-book'></i>
                <span class="link_name">Equipement & Population</span>
            </a>
        </li>
      <li>
        <div class="iocn-link">
          <a href="#">
              <i class='bx bx-wallet-alt'></i>
            <span class="link_name">Expenses</span>
          </a>
          <i class='bx bxs-chevron-down arrow' ></i>
        </div>
        <ul class="sub-menu">
          <li><a href="Employee_Expense.php">Employee Expense</a></li>
          <li><a href="Infrastructural_Expense.php">Infrastructural Expense</a></li>
          <li><a href="Other_Expense.php">Other Expense</a></li>
        </ul>
      </li>      
      <li>
        <a href="#">
            <i class='bx bxs-report'></i>
          <span class="link_name">Reports</span>
        </a>
      </li>
     
      <li>
    <div class="profile-details">
      <div class="profile-content">
        <!--<img src="image/profile.jpg" alt="profileImg">-->
      </div>
      <div class="name-job">
        <div class="profile_name"><?php echo $Name; ?></div>
        <div class="job"><?php echo $Designation; ?></div>
      </div>
        <a href="Logout.php">
            <i class='bx bx-log-out'></i>
        </a>
      
    </div>
  </li>
</ul>
  </div>
  <section class="home-section">
      <nav>
          <div class="home-content" style="margin-top:15px">
              <span class="text">TIV Sales Data</span>
          </div>  
      </nav>
          <br />
          <!-- Body Content-->
      <div class="main" style="top:50px;bottom:20px">

          <div>             

                <form method="POST" action="">
                   <p>Select Month: <input type="month" name="month" placeholder="Select Month" required style="width:auto;border:solid; border-color:black;font-family:Cambria;border-radius:5px;height:30px" /> </p>
 

                    <table class="table">
                        <tr>
                            <th style="width:50px">#</th>
                            <th>District</th>
                            <th>Brand</th>
                            <th>Category</th>
                            <th>Sub Category</th>
                            <th>Model</th>
                            <th style="width:80px">Quantity</th>
                            <th>Average Selling Price</th>
                        </tr>
                        <tbody id="tbody">
                            <template id="row-template">
                                  <tr style="text-align: center" class="parent-container">
                                        <td></td>
                                      <td>
                                            <select class="background" name="District[]">
                                                  <option value="">District</option>                                                 
                                            </select>
                                        </td>
                                        <td>
                                            <select id="Brand" name="Brand[]" class="Brand">
                                            <option value="">Select Brand</option>
                                            <?php 
                                            $query = "SELECT * FROM brand ORDER BY Brand_Name ASC"; 
                                            $result = $conn->query($query); 
                                            if($result->num_rows > 0){ 
                                                while($row = $result->fetch_assoc()){  
                                                    echo '<option value="'.$row['Brand_ID'].'">'.$row['Brand_Name'].'</option>'; 
                                                } 
                                            }else{ 
                                                echo '<option value="">Country not available</option>'; 
                                            } 
                                            ?>
                                        </select>
                                        </td>
                                      <td>
                                            <select id="Category" name="Category[]" class="Category">
                                                  <option value="">Select Brand first</option>
                                            </select>
                                        </td>
                                      <td>
                                            <select id="Sub_Category" name="Sub_Category[]" class="Sub_Category">
                                                  <option value="">Select Category first</option>
                                            </select>
                                        </td>                                     

                                      <td>
                                            <select  id="Model" name="Model[]" class="Model">
                                                  <option value="">Select Sub-Category first</option>
                                            </select>
                                        </td>
                                        <td><input type='number' name="Quantity[]"></td>
                                        <td><input type='number' name="ASP[]"></td>
                                      <td hidden align='center' style="width:10%">
                                    <input type="checkbox" checked="checked" class="checkbox" name='lang[]' value="<?php echo $ID; ?>" />
                                </td>
                                  </tr>
                                </template>
                        </tbody>
                    </table>

                    <div style="text-align:center">
                        <button type="button" onclick="addItem();" style="font-family:Cambria;float:left;background: #0A2558;color:white;cursor:pointer; height:30px; border-radius:5px; padding:5px">Add New<i class='bx bx-plus-medical' style="margin-left:10px"></i></button>
                        <input type="submit" name="addInvoice" value="Submit" style="width:100px;background: #0A2558; color:white;font-family:Cambria;border-radius:5px;height:30px;" />
                    </div>
                </form>

               <?php
               if (isset($_POST["addInvoice"]))
               {
                   $month = $_POST["month"];
                   $Dealername = $Name;

                   $newDate = date("M-Y", strtotime($month));

                   //for ($a = 0; $a < count($_POST["lang"]); $a++)
                   foreach($_POST['lang'] as $ID => $VAL){
                       $Brand = $_POST['Brand'] [$ID];
                       $Category = $_POST['Category'] [$ID];
                       $Sub_Category = $_POST['Sub_Category'] [$ID];
                       $Model = $_POST['Model'] [$ID];
                       $Quantity = $_POST['Quantity'] [$ID];
                       $ASP = $_POST['ASP'] [$ID];
                       $District = $_POST['District'] [$ID];

                       $sql = "INSERT INTO tiv (Month, Brand, Category, Sub_Category, Model, Quantity, Dealer_Name, District, ASP) VALUES ('$newDate', '$Brand', '$Category', '$Sub_Category', '$Model', '$Quantity', '$Dealername', '$District', '$ASP')";
                       mysqli_query($conn, $sql);
                   }
               }
               ?>

                <script>
	                        const template=document.getElementById('row-template');
                            const tbody=document.getElementById('tbody');
                            let itemCount=0;
  
                            function addItem(){
  	                            const newRow = template.content.cloneNode(true);
                                const firstTd = newRow.querySelector('td:first-child');
                                firstTd.textContent=++itemCount;
                                tbody.appendChild(newRow);
                            }
                </script>
            </div>
          
      </div>
</section>

        <script>
            $(document).on('change', '.Brand', function(){
                var BrandID = $(this).val();
                if(BrandID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Brand_ID='+BrandID,
                        success: function (html) {
                            $('#Category').html(html);
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#Category').html('<option value="">Select Brand first</option>');
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.Category', function(){
                var CategoryID = $(this).val();
                if(CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Category_ID='+CategoryID,
                        success: function (html) {
                            $('#Sub_Category').html(html);
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#Sub_Category').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.Sub_Category', function(){
                var Sub_CategoryID = $(this).val();
                if(Sub_CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Sub_Category_ID='+Sub_CategoryID,
                        success: function (html) {
                            $('#Model').html(html);
                        }
                    }); 
                } else {
                            BrandID.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });
    
        </script>

        <script>
                function Category_click_click(){
                value_select = $("#Category_click").val();
                $.post('TIV.php',{"Category_click":value_select},function(data){
                })
                }
        </script>

        <script>
                function Sub_Category_click(){
                value_select = $("#Sub_Category").val();
                $.post('TIV.php',{"Sub_Category":value_select},function(data){
                })
                }
        </script>

    <script>
          let arrow = document.querySelectorAll(".arrow");
          for (var i = 0; i < arrow.length; i++) {
            arrow[i].addEventListener("click", (e)=>{
           let arrowParent = e.target.parentElement.parentElement;//selecting main parent of arrow
           arrowParent.classList.toggle("showMenu");
            });
          }
          let sidebar = document.querySelector(".sidebar");
          let sidebarBtn = document.querySelector(".bx-menu");
          console.log(sidebarBtn);
          sidebarBtn.addEventListener("click", ()=>{
            sidebar.classList.toggle("close");
          });
    </script>
</body>
</html>

 

<?php
// Include the database config file
include("../connection.php");
//error_reporting(0);
error_reporting(E_ALL);

ini_set('display_errors', '1');
//ini_set('display_errors','Off');

if(!empty($_POST["Brand_ID"])){
    // Fetch state data based on the specific country
    // Generate HTML of state options list
   $query = "SELECT distinct Category_Name FROM model WHERE Brand_ID = ".$_POST['Brand_ID']." ";
    $result = $conn->query($query);
        if($result->num_rows > 0){
            echo '<option value="">Select Category</option>';
             while($row = $result->fetch_assoc()){
                 echo '<option value="'.$row['Category_ID'].'">'.$row['Category_Name'].'</option>';
              }
        }else{
            echo '<option value="">Category not available</option>';
        }
}elseif(!empty($_POST["Category_ID"])){
    // Fetch city data based on the specific state
    $query = "SELECT distinct Sub_Category_Name FROM model WHERE Sub_Category_ID = ".$_POST['Category_ID']." ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Sub-Category</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Sub_Category_ID'].'">'.$row['Sub_Category_Name'].'</option>';
        }
    }else{
        echo '<option value="">Sub-Category available</option>';
    }
}elseif(!empty($_POST["Sub_Category_ID"])){
    // Fetch city data based on the specific state
    $query = "SELECT distinct Model_Name FROM model WHERE Model_ID = ".$_POST['Sub_Category_ID']." ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Model</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Model_ID'].'">'.$row['Model_Name'].'</option>';
        }
    }else{
        echo '<option value="">Model available</option>';
    }
}
?>

 

Pls look on it. If you found any mistakes, pls correct it 

Dear Ginerjm,

 

I turned ON the error reporting and fount the mistakes and corrected. Now all my drop downs are populating the values.

But it is dosplaying on forst row only. If i add additional rows and select the brand, then it is changing the values on forst row only. It is not changing on my newly added row. 

Dear Team,

Now i am getting output for all the four drop down list based on the selection of previous dropdown. My final code is 

<?php

session_start();
//error_reporting(0);
error_reporting(E_ALL);

ini_set('display_errors', '1');
//ini_set('display_errors','Off');
include("../connection.php");
include("../paginator.class.php");

$id=$_SESSION['id'];

if($_SESSION['id'] == '') {
    session_destroy();
    // header("location:logout.php"); //redirect to index.php
}

$query=mysqli_query($conn,"SELECT * FROM users where id='$id'");
$row=mysqli_fetch_array($query);
$Name = $row['Name'];
$Emp_No = $row['Emp_No'];
$Designation = $row['Designation'];
$Type = $row['User_Type'];
$Type1 = $row['User_Type'];
$Branch = $row['Branch'];
$Approver = $row['Approver'];

?>



<!DOCTYPE html>
<!-- Created by CodingLab |www.youtube.com/CodingLabYT-->
<html lang="en" dir="ltr">
  <head>
    <meta charset="UTF-8">
    <!--<title> Drop Down Sidebar Menu | CodingLab </title>-->
    <link rel="stylesheet" href="css/tiv.css">
    <!-- Boxiocns CDN Link -->
    <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">

      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

      <script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
      <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

   </head>
<body>
  <div class="sidebar">
    <div class="logo-details">
        <img src="Image/Schwing_Logo.jpg" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
        <img src="Image/XCMG_LOGO.png" style="height:30px; width:100px; margin-left:10px; margin-top:0px" />
    </div>
    <ul class="nav-links">
      <li>
        <a href="Dashboard.php" >
            <i class='bx bxs-dashboard'></i>
          <span class="link_name">Dashboard</span>
        </a>
      </li>
        <li>
            <a href="TIV.php" class="active">
                <i class='bx bx-trending-up'></i>
                <span class="link_name">TIV Sales Data</span>
            </a>
        </li>
        <li>
            <a href="Marketing.php">
                <i class='bx bxs-business'></i>
                <span class="link_name">Marketing & Promotion</span>
            </a>
        </li>
        <li>
            <a href="PartsandService.php">
                <i class='bx bxs-wrench'></i>
                <span class="link_name">Parts & Service</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bxs-user-detail'></i>
                <span class="link_name">Manpower</span>
            </a>
        </li>
        <li>
            <a href="Manpower.php">
                <i class='bx bx-book'></i>
                <span class="link_name">Equipement & Population</span>
            </a>
        </li>
      <li>
        <div class="iocn-link">
          <a href="#">
              <i class='bx bx-wallet-alt'></i>
            <span class="link_name">Expenses</span>
          </a>
          <i class='bx bxs-chevron-down arrow' ></i>
        </div>
        <ul class="sub-menu">
          <li><a href="Employee_Expense.php">Employee Expense</a></li>
          <li><a href="Infrastructural_Expense.php">Infrastructural Expense</a></li>
          <li><a href="Other_Expense.php">Other Expense</a></li>
        </ul>
      </li>      
      <li>
        <a href="#">
            <i class='bx bxs-report'></i>
          <span class="link_name">Reports</span>
        </a>
      </li>
     
      <li>
    <div class="profile-details">
      <div class="profile-content">
        <!--<img src="image/profile.jpg" alt="profileImg">-->
      </div>
      <div class="name-job">
        <div class="profile_name"><?php echo $Name; ?></div>
        <div class="job"><?php echo $Designation; ?></div>
      </div>
        <a href="Logout.php">
            <i class='bx bx-log-out'></i>
        </a>
      
    </div>
  </li>
</ul>
  </div>
  <section class="home-section">
      <nav>
          <div class="home-content" style="margin-top:15px">
              <span class="text">TIV Sales Data</span>
          </div>  
      </nav>
          <br />
          <!-- Body Content-->
      <div class="main" style="top:50px;bottom:20px">

          <div>             

                <form method="POST" action="">
                   <p>Select Month: <input type="month" name="month" placeholder="Select Month" required style="width:auto;border:solid; border-color:black;font-family:Cambria;border-radius:5px;height:30px" /> </p>
 

                    <table class="table">
                        <tr>
                            <th style="width:50px">#</th>
                            <th>District</th>
                            <th>Brand</th>
                            <th>Category</th>
                            <th>Sub Category</th>
                            <th>Model</th>
                            <th style="width:80px">Quantity</th>
                            <th>Average Selling Price</th>
                        </tr>
                        <tbody id="tbody">
                            <template id="row-template">
                                  <tr style="text-align: center" class="parent-container">
                                        <td></td>
                                      <td>
                                            <select class="background" name="District[]">
                                                  <option value="">District</option>                                                 
                                            </select>
                                        </td>
                                        <td>
                                            <select id="Brand" name="Brand[]" class="Brand">
                                            <option value="">Select Brand</option>
                                            <?php 
                                            $query = "SELECT * FROM brand ORDER BY Brand_Name ASC"; 
                                            $result = $conn->query($query); 
                                            if($result->num_rows > 0){ 
                                                while($row = $result->fetch_assoc()){  
                                                    echo '<option value="'.$row['Brand_ID'].'">'.$row['Brand_Name'].'</option>'; 
                                                } 
                                            }else{ 
                                                echo '<option value="">Country not available</option>'; 
                                            } 
                                            ?>
                                        </select>
                                        </td>
                                      <td>
                                            <select id="Category" name="Category[]" class="Category">
                                                  <option value="">Select Brand first</option>
                                            </select>
                                        </td>
                                      <td>
                                            <select id="test" name="test[]" class="test">
                                                  <option value="">Select Category first</option>
                                            </select>
                                        </td>                                     

                                      <td>
                                            <select  id="Model" name="Model[]" class="Model">
                                                  <option value="">Select Sub-Category first</option>
                                            </select>
                                        </td>
                                        <td><input type='number' name="Quantity[]"></td>
                                        <td><input type='number' name="ASP[]"></td>
                                      <td hidden align='center' style="width:10%">
                                    <input type="checkbox" checked="checked" class="checkbox" name='lang[]' value="" />
                                </td>
                                  </tr>
                                </template>
                        </tbody>
                    </table>

                    <div style="text-align:center">
                        <button type="button" onclick="addItem();" style="font-family:Cambria;float:left;background: #0A2558;color:white;cursor:pointer; height:30px; border-radius:5px; padding:5px">Add New<i class='bx bx-plus-medical' style="margin-left:10px"></i></button>
                        <input type="submit" name="addInvoice" value="Submit" style="width:100px;background: #0A2558; color:white;font-family:Cambria;border-radius:5px;height:30px;" />
                    </div>
                </form>

               <?php
               if (isset($_POST["addInvoice"]))
               {
                   $month = $_POST["month"];
                   $Dealername = $Name;

                   $newDate = date("M-Y", strtotime($month));

                   //for ($a = 0; $a < count($_POST["lang"]); $a++)
                   foreach($_POST['lang'] as $ID => $VAL){
                       $Brand = $_POST['Brand'] [$ID];
                       $Category = $_POST['Category'] [$ID];
                       $Sub_Category = $_POST['Sub_Category'] [$ID];
                       $Model = $_POST['Model'] [$ID];
                       $Quantity = $_POST['Quantity'] [$ID];
                       $ASP = $_POST['ASP'] [$ID];
                       $District = $_POST['District'] [$ID];

                       $sql = "INSERT INTO tiv (Month, Brand, Category, Sub_Category, Model, Quantity, Dealer_Name, District, ASP) VALUES ('$newDate', '$Brand', '$Category', '$Sub_Category', '$Model', '$Quantity', '$Dealername', '$District', '$ASP')";
                       mysqli_query($conn, $sql);
                   }
               }
               ?>

                <script>
	                        const template=document.getElementById('row-template');
                            const tbody=document.getElementById('tbody');
                            let itemCount=0;
  
                            function addItem(){
  	                            const newRow = template.content.cloneNode(true);
                                const firstTd = newRow.querySelector('td:first-child');
                                firstTd.textContent=++itemCount;
                                tbody.appendChild(newRow);
                            }
                </script>
            </div>
          
      </div>
</section>

        <script>
            $(document).on('change', '#Brand', function(){
                var BrandID = $(this).val();
                if(BrandID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Brand_ID='+BrandID,
                        success: function (html) {
                            $('#Category').html(html);
                            $('#test').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#Category').html('<option value="">Select Brand first</option>');
                            $('#test').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '#Category', function(){
                var CategoryID = $(this).val();
                var BrandID = $('#Brand').val();
                if(CategoryID){
                    $.ajax({
                        type:'GET',
                        url:'ajaxData.php',
                        //data: 'Category_ID=' + CategoryID,
                       data: 'Category_ID='+CategoryID+'&Brand_ID='+BrandID,
                        success: function (html) {
                            $('#test').html(html);
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            $('#test').html('<option value="">Select Category first</option>');
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '#test', function(){
                var subCategoryID = $(this).val();
                var CategoryID = $('#Category').val();
                var BrandID = $('#Brand').val();
                if(subCategoryID){
                    $.ajax({
                        type:'GET',
                        url:'ajaxData.php',
                        //data: 'Category_ID=' + CategoryID,
                       data: 'Sub_Category_ID='+subCategoryID+'&Brand_ID='+BrandID,
                        success: function (html) {
                            $('#Model').html(html);
                        }
                    }); 
                } else {
                            $('#Model').html('<option value="">Select Sub_Category first</option>');
                }
            });
    
        </script>

        <script>
                function Category_click_click(){
                value_select = $("#Category_click").val();
                $.post('TIV.php',{"Category_click":value_select},function(data){
                })
                }
        </script>


    <script>
          let arrow = document.querySelectorAll(".arrow");
          for (var i = 0; i < arrow.length; i++) {
            arrow[i].addEventListener("click", (e)=>{
           let arrowParent = e.target.parentElement.parentElement;//selecting main parent of arrow
           arrowParent.classList.toggle("showMenu");
            });
          }

    </script>
</body>
</html>

 

<?php
// Include the database config file
include("../connection.php");
//error_reporting(0);
error_reporting(E_ALL);

ini_set('display_errors', '1');
//ini_set('display_errors','Off');

if(!empty($_POST["Brand_ID"])){
    $Brand =$_POST["Brand_ID"];
    // Fetch state data based on the specific country
    // Generate HTML of state options list
    $query = "SELECT distinct Category_Name, Category_ID FROM model WHERE Brand_ID = '$Brand' ";
    $result = $conn->query($query);
        if($result->num_rows > 0){
            echo '<option value="">Select Category</option>';
             while($row = $result->fetch_assoc()){
                // echo '<option value="'.$row['Category_ID'].'">'.$row['Category_Name'].'</option>';
                 echo '<option value="' . $row['Category_ID'] . '">' . $row['Category_Name'] . '</option>';
              }
        }else{
            echo '<option value="">Category not available</option>';
        }
}elseif(isset($_GET['Category_ID'])){
    $Brand =$_GET["Brand_ID"];
    $Category =$_GET["Category_ID"];

    // Fetch city data based on the specific state
    $query = "SELECT distinct Sub_Category_Name, Sub_Category_ID FROM model WHERE Category_ID = '$Category' AND Brand_ID = '$Brand'  ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Sub-Category</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Sub_Category_ID'].'">'.$row['Sub_Category_Name'].'</option>';
        }
    }else{
        echo '<option value="">Sub-Category Not Available</option>';
    }
}elseif(isset($_GET['Sub_Category_ID'])){
    $Brand =$_GET["Brand_ID"];
   // $Category =$_GET["Category_ID"];
    $Sub_Category =$_GET["Sub_Category_ID"];
    // Fetch city data based on the specific state
    $query = "SELECT distinct Model_Name, Model_ID FROM model WHERE Sub_Category_ID = '$Sub_Category' AND Brand_ID = '$Brand' ";
    $result = $conn->query($query);

    // Generate HTML of city options list
    if($result->num_rows > 0){
        echo '<option value="">Select Model</option>';
        while($row = $result->fetch_assoc()){
            echo '<option value="'.$row['Model_ID'].'">'.$row['Model_Name'].'</option>';
        }
    }else{
        echo '<option value="">Model Not Available</option>';
    }
}
?>

But the other problem i am facing on this is the drop down is not working for newly added row. If i select the brand in newly added row, it is changing the value of my first row. But it shout change the row where i selected it.

 

please help me how to populate the datan on which row i am selecting

13 minutes ago, Senthilkumar said:

is not working for newly added row

if you read the information that I posted, you will know why this doesn't work. you CANNOT repeat ids in the markup. you must use some other way of referencing the elements. i showed code to do this by finding the .closest parent container, then .finding an element with a class name within the parent container.

the reason no one is posting fixed code is because you would not learn anything by just repeating what you see. programming is a writing and reading activity. you must actually understand the meaning of the words and syntax you are using. copy/pasting something that someone else writes doesn't do this.

  • Great Answer 1

Dear Gyver,

As per your instruction i modified the code. My modified code is 

$(document).on('change', '.Brand', function(){
                //var BrandID = $(this).val();
                var parent = $(this).closest('.parent-container');
                if(parent){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Brand_ID='+parent,
                        success: function (html) {
                            parent.find('.Category').html(html);
                            parent.find('.test').html('<option value="">Select Category first</option>');
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            parent.find('.Category').html('<option value="">Select Brand first</option>');
                            parent.find('.test').html('<option value="">Select Category first</option>');
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

When i am selecting Brand, the brand id is posting as object. pls refer the below image

image.thumb.png.b4e8f4da0957c2c7427649cf08ae63bd.png

kindly modify my code this time

Edited by Senthilkumar
On 4/16/2023 at 12:35 PM, Senthilkumar said:
            $(document).on('change', '.Brand', function(){
                var BrandID = $(this).val();
                if(BrandID){

^^^ this part of the code gets the selected brand id and calls the ajax code. why did you change this part of the code?

the part you need to change is the code that uses the result of the ajax call.

Dear Gyver,

I changed the script as per your suggession. Now all are working properly.

My final code is 

<script>
            $(document).on('change', '.Brand', function(){
                var BrandID = $(this).val();
                var parent = $(this).closest('.parent-container');
                if(BrandID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data:'Brand_Name='+BrandID,
                        success: function (html) {
                            parent.find('.Category').html(html);
                            parent.find('.SubCategory').html('<option value="">Select Category first</option>');
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            parent.find('.Category').html('<option value="">Select Brand first</option>');
                            parent.find('.SubCategory').html('<option value="">Select Category first</option>');
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.Category', function(){
                var CategoryID = $(this).val();                
                var parent = $(this).closest('.parent-container');
                    var BrandID = parent.find('#Brand').val();
                if(CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data: 'Category_Name='+CategoryID+'&Brand_Name='+BrandID,
                        success: function (html) {
                            parent.find('.SubCategory').html(html);
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                        }
                    }); 
                } else {
                            parent.find('.SubCategory').html('<option value="">Select Category first</option>');
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            $(document).on('change', '.SubCategory', function(){
                var SubCategoryID = $(this).val();               
                var parent = $(this).closest('.parent-container');
                 var BrandID = parent.find('#Brand').val();
                var CategoryID = parent.find('#Category').val();
                if(CategoryID){
                    $.ajax({
                        type:'POST',
                        url:'ajaxData.php',
                        data: 'Sub_Category_Name='+SubCategoryID+'&Category_Name='+CategoryID+'&Brand_Name='+BrandID,
                        success: function (html) {
                            parent.find('.Model').html(html);
                        }
                    }); 
                } else {
                            parent.find('.Model').html('<option value="">Select Sub_Category first</option>');
                }
            });

            
    
        </script>

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.