CodeIgniter tutorial on dynamically populating the second dropdown based on the selection of the first dropdown menu

I have been working on a task to create two dependent drop-down lists (penalty_type based on vehicle_type). Is there anyone willing to help me with the implementation? Here is my code:

This is the Controller code snippet:

public function index()
    {
    $data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
        $data['penality_type'] = $this->vehicle_type_model->getAllPenalityType();
         $this->load->view('admin/penality_type_price/view_penality_type_price', $data);
    }

This is the vehicle_type_model code:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class vehicle_type_model extends CI_Model {

    /*
    * Get All Vehicle types
    */

    public function getAllVtype()
    {
        $result = $this->db->get('vehicle_type');
        return $result->result_array();
    }


        public function getAllPenalityType()
    {
        $result = $this->db->get('penality_type');
        return $result->result_array();
    }

}

This is the View snippet:

    <div class="form-group">
            <label for="vehicle_type_id">Vehicle Type</label>
            <select name="vehicle_type_id" class="form-control vehicle_type_id">
                <option value="">Select Vehicle type</option>
            </select>

        </div>

    <div class="form-group">
            <label for="penality_type_id">penality type</label>
            <select name="penality_type_id" class="form-control penality_type_id">
                <option value="">Select penality type</option>
            </select>  
    </div>

Answer №1

Your current approach is incorrect. It seems that the penalty type is associated with the vehicle type. To achieve this, you should pass the vehicle_type ID through AJAX to the controller, then to the database, and finally load the data into the penalty type drop-down menu.

Here is a sample code snippet to guide you:

Your index function should look like this:

public function index()
{
    $data['vehicle_type'] = $this->vehicle_type_model->getAllVtype();
    $this->load->view('admin/penality_type_price/view_penality_type_price', $data);
}

For the view part:

<div class="form-group">
   <label for="vehicle_type_id">Vehicle Type</label>
   <select name="vehicle_type" class="form-control vehicle_type_id" id = "vehicle_type">
       <option value="">Select Vehicle type</option>
       <?php foreach($vehicle_type as $row) { ?>
            <option value="<?php echo $row->vehicle_type_id ?>"><?php echo $row->vehicle_type_name; ?></option>
       <?php } ?>
   </select>
</div>

AJAX Code:

var base_url = "<?php echo base_url(); ?>";
$("#vehicle_type").change(function () {
        if ($('#vehicle_type').val() != "") {
            $.ajax({
                url: base_url + "your_controller/get_penality_by_id",
                type: 'POST',
                cache: false,
                data: {
                    'vehicle_type_id': $('#vehicle_type').val()
                },
                success: function (data) {
                    if($data){
                       $("#penality_type").html(data);
                    }
                }
            });
        }
    });

Controller:

public function get_penality_by_id(){
    $vehicle_type_id = $this->input->post('vehicle_type_id');
    $data = array('vehicle_type_id' => $vehicle_type_id);
    $result = $this->your_model_name->get_penality($data);

    if($result){
       $option = "<option value=''>--Select an Option--</option>";
       foreach ($result as $row){
           $option .= "<option value='".$row->penality_id."'>".$row->penality_name."</option>";             
       }
       echo $option;
    }else{
       echo $option = "<option value=''>--Select an Option--</option>";
  }
}

Model:

public function get_penality($data){
   $this->db->select('*');
   $this->db->from('table-name');
   $this->db->where($data);
   $result_set = $this->db->get();
   if($result_set->num_rows() > 0){
      return $result_set->result();
   }
   else {
      return FALSE;
   }
}

Make sure to include the vehicle type ID in the drop-down options to fetch the corresponding penalty. I hope this explanation helps you.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The concatenation function in JavaScript does not seem to be functioning properly with JSON

My attempt to use .concat() in order to combine two objects is resulting in tiles.concat is not a function The following code (in an angular app and written in coffeescript): $scope.tiles = new UI(); $scope.tiles.loadUITiles(); console.log($sco ...

Having trouble getting a response when using formidable in Next.js?

I am working on uploading a file from the front end to my GCP workflow, and everything seems to be functioning correctly. However, I am consistently encountering an issue where the API resolved without sending a response message appears. I attempted to r ...

Extract information from a Web Service using Javascript

As a novice in web app development, I am currently working on creating a login page and retrieving user data from a local database using JavaScript. Despite my efforts, I seem to have made an error somewhere in my code. Below is the snippet of my JavaScrip ...

One of the three identical paths in Node.JS is experiencing issues

I'm brand new to Node.js and currently working on creating a backend api for a project. I have 3 routes in my application: societies, users, and emails. //module for email functionality emailsModule = require('./api/routes/emails')(co ...

What is the best way to show a nested div element within a v-for loop in Vue.js?

One interesting feature of my coding project is that I have an array nested within another array, and I iterate through them using two v-for loops. The challenge arises when I try to display a specific div in the second loop only upon clicking a button. ...

navigating to the start of a hyperlink

I'm having issues with scrolling to anchors and encountering 3 specific problems: If I hover over two panels and click a link to one of them, nothing happens. When I'm on section D and click on section C, it scrolls to the end of section C. ...

A guide on instantly updating displayed flat/section list elements in React Native

I am in the process of creating a screen called ContactListScreen. The direct child of ContactListScreen is ContactItems, which is a sectionList responsible for rendering each individual ContactItem. However, I have encountered a problem where my ContactIt ...

Retrieving the value of the option that has been selected from a dropdown

I have successfully implemented a drop-down menu with the following code: // Creating a select element for priority within a form in the bottom row div const formPriority = document.createElement("select"); formPriority.setAttribute("name","project"); form ...

What is the best way to store the result of a mongoose query in a global variable in Node.js?

I retrieved results from the Mongo database and saved them in a variable within a function. However, I am unable to access that variable outside of the function. How can I resolve this issue? Currently, I can see the results inside the function using the ...

Utilizing AJAX for sending data to a PHP database and automatically updating the page

Currently, I've implemented a button: <ul> <li><button onclick="display('1')">1</button></li> <li><button onclick="display('2')">2</button></li> <li><butto ...

JavaScript - Loading image from local file on Linux machine

I have a server running and serving an HTML page, but I am trying to display an image from a local drive on a Linux machine. I've tried using file://.., but it doesn't seem to be working for me on Ubuntu 18.04. There are no errors, the img tag ju ...

Is it possible to modify the default behavior of a sensitive region within a button?

I created a calculator application in React and overall, it's working fine, however... I've noticed that when I hold a click longer, it only registers as a click if the mouse was pressed down and released on the button itself. Although I unders ...

Use jQuery and AJAX to seamlessly upload images

Currently, I am attempting to utilize ajax to upload a photo. Here is the input I am working with: <input type="file" name="defaultPhoto"> Here is a snippet of my jQuery code: var form = #insertCredentials var defaultPhoto = $('#' + fo ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Distinguishing between if(a) and if(a!=null && a!=undefined)

While attempting to populate data in the DOM, I am encountering numerous issues due to the absence of values in the objects or arrays I am trying to utilize. Take, for instance, the following object: var obj = { name: 'rajat', age: 20 } Gi ...

Tips on transmitting checkbox data from AJAX to PHP

I'm currently working with this code and facing an issue where data from checkboxes is being sent to PHP one by one. I want to be able to send multiple selected data at once. How can I modify the code to achieve this? $('#lunas').click(funct ...

Using radio buttons to toggle the visibility of a div element within a WordPress website

I am currently working on creating a WordPress page using the custom page tool in the admin interface. My goal is to have 3 radio buttons, with 2 visible and 1 hidden. The hidden button should be automatically checked to display the correct div (although ...

Tips for utilizing the track OrbitControls in three.js

Presently, there are two blocks visible within the space: const material1 = new THREE.MeshBasicMaterial({color: '#00ff00'}); const cube1 = new THREE.Mesh(geometry, material1); cube1.position.set(0, 0, 0); const material2 = new THREE.MeshBasicMat ...

Tips for selecting a specific item in a list using onClick while iterating through a JSON array in React

I have a unique JSON file filled with an array of objects, each containing a "Question" and "Answer" pair (I am working on creating an FAQ section). My current task involves mapping through this array to display the list of questions, a process that is fun ...

Issues with the OnChange function not properly functioning in duplicate input fields

I've designed a form that allows for adding or deleting rows, effectively cloning input fields. One of the input fields utilizes Jquery Ajax to retrieve its value. However, upon adding an extra row by cloning the parent row to generate a child row, th ...