Using JavaScript and Codigniter to populate a drop down box with an array

One of the key elements in my Codeigniter project is the $location variable, which is set using sessions and can represent cities like 'Austin', 'Houston', and so on. Each location has its own unique tours to offer. Instead of manually populating the dropdown box with available tours at a specific location, I'm looking for some JavaScript examples that can automate this process. The validation of this dropdown will be handled in the respective controller.

<?php
$location = $this->session->userdata('location');

// Need JavaScript logic here to determine the current location and populate options_tour array.
// The array will be used as options in form_dropdown() function.

//form ...
$data_tour = 'class="span12"';
$tour = array('style' => 'font-weight:bold;');
echo form_label('Select Tour: ','tour', $tour);
echo form_dropdown('tour', $options_tour, '', $data_tour);
    ?>
 

Answer №1

If you want to populate the form with JavaScript in this way, you'll need to take a slightly indirect approach.

One option is to create a hidden field that JavaScript can read to get the value of the $location variable, or you could make an ajax call to retrieve it.

Then, you can create a JavaScript function that will return the appropriate values based on the location. For example:

function get_tours(location){

    var tours = {};

    switch(location){
        case 'Austin':
            tours = { "City Center": { 
                        "text": "City Center", 
                        "value": "city_center"
                      }
                    };
        break;

        //etc...
    }

    return tours;
}

If you opt for the AJAX method, you'll need to call the tour option setting function when the AJAX request succeeds.

Once you have the tour information in your JavaScript variable, you can update the elements of the 'tour' element on the page that was initially generated by PHP like so:

function create_tour_options(tours){
    var select = document.getElementById('tour');

    for(var tour in tours){
        var tour_option = document.createElement('option');
        tour_option.value = tours[tour]['value'];
        tour_option.text = tours[tour]['text'];
        select.appendChild(tour_option);
    }

    // Creating a new select object and replacing the existing one may be more efficient than adding and removing individual options.
}

Alternatively, if using JavaScript is not mandatory, you could write a PHP function to achieve the same result and return the $options_tour variable. For example:

function get_tours($location='Austin'){
    $tours = array();

    switch ($location){
        case 'Austin':
            $tours = array( "text" => "City Center", 
                            "value" => "city_center"
                          );
        break;

        //etc...
    }

    return $tours;
}

Using PHP might be preferable as the options will be generated during the initial page load and won't need to be inserted afterwards.

Additionally, I've provided examples using vanilla JavaScript since I'm unsure if you're using JQuery or not.

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

How can MessagePorts be effectively utilized in electron Js?

What are some real-world applications of using MessagePorts in Electron JS? Why is it necessary instead of just using ipcRenderer.invoke? I haven't been able to identify any practical scenarios where MessagePorts are indispensable. It seems like it&ap ...

Creating an app using Ionic 1 that features scrollable tabs with the ability to handle overflow

My current code snippet is displayed below. On smaller mobile screens, all 7 tabs are not visible at once and instead appear in two rows which looks messy. I want to modify the display so that only 3 tabs are visible at a time and can be scrolled through. ...

Can someone help me with combining these two HTML and JavaScript files?

I successfully created an HTML/JavaScript file that functions properly: <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor ...

Trouble accessing Strapi CMS data on Next.js frontend using React.js

Currently, I am in the process of developing a website using Strapi as the CMS and Next.js(React) for the Frontend. The website features an image slider that includes an image, a headline, and a description. I am trying to retrieve these elements from my S ...

Restrict HTML Content in Json Result using PHP and Jquery

I'm currently working with a Controller that outputs JSON response and a JavaScript function that appends that response to the last tr in an HTML table. <pre> $reponse="<tr class=\"border_bottom\"><td>My Repo ...

Using PHP/JavaScript to activate a button once the timer reaches 00:00

I came across a JavaScript fiddle code that is working perfectly. Here it is: HTML <div id="worked">00:05</div> JS $(document).ready(function (e) { var $worked = $("#worked"); function update() { var myTime = $worked.h ...

Issues with Codeigniter Ajax Post functionality

Hey everyone, I'm working on implementing a simple voting system for comments using jQuery Ajax to avoid page refreshing when someone likes or dislikes a comment. Here is the jQuery code I have so far: $(document).ready(function(){ $(".vote-btn" ...

transferring a multidimensional array from controller to view within the CodeIgniter framework

I am currently facing an issue while trying to create a versatile function called test that can be utilized for various types of buildings, as I am struggling to pass the variables into the View. Here is the Controller code: public function index($data = ...

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

How can I retrieve the total number of records (count) in an XML response using PostMan?

Hello, I'm currently attempting to determine the length of an XML response but I'm running into some issues. The error message I am encountering is as follows: "There was an error in evaluating the test script: ReferenceError: xml2json is not def ...

When using Node.js, res.render may encounter issues, but res.send typically functions properly

Currently, I am in the process of setting up the environment for a node.js app. Unfortunately, I am encountering an issue where the views/ejs files are not being rendered properly. When I use the following code snippet: app.get("/", function(req, res){ ...

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

Issue with RegisterClientScriptCode function following a partial postback

In a SharePoint website, the code below is contained within a user control: ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "jquery144", "<script type=\"text/javascript\" src=\"/_layouts/Unicre.Web.RUOnline.Controlos/Script ...

Managing numerous JavaScript objects within a plugin

I have developed a straightforward javascript plugin that enables me to gather data from specific html elements. A page can contain x number of elements (usually up to 20), each with its own settings. However, the issue I am facing is that the returned obj ...

Hide the dropdown menu when the user clicks anywhere else on the screen

I have a scenario with 2 dropdown buttons. When I click outside the dropdown or on it, it closes. However, if I click on the other dropdown button, it does not close and the other one opens. I want them to close when I click on the other button or anywhere ...

In Visual Studio Code, beautification feature splits HTML attributes onto separate lines, improving readability and code organization. Unfortunately, the print width setting does not apply

I have done extensive research and tried numerous solutions, When using Angular and formatting HTML with Prettier, it appears quite messy as it wraps each attribute to a new line, for example: <button pButton class="btn" ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

What causes the discrepancy in smoothness between the JavaScript animation when offline versus its choppiness when online, particularly on AWS

Recently I delved into game development using HTML5/CSS/JS and embarked on a small project. Check out the game here at this AWS storage link: If you open the game and press SPACE, you'll notice that the ball starts moving with occasional brief pauses ...

Strategies for refining the names in the dropdown options using AngularJS

I am working with a select element that has a name and id as options value. I am also adding '-' along with the name. However, there is a scenario where the name will be empty and in that case, the '-' should not be displayed. The expe ...

Saving changes made in HTML is not supported when a checkbox is selected and the page is navigated in a React application using Bootstrap

In my array, there are multiple "question" elements with a similar structure like this: <><div className="row"><div className="col-12 col-md-9 col-lg-10 col-xl-10 col-xxl-10"><span>Question 1</span></div ...