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

Is it possible to verify the data within a VueJS model? It seems that none of the Vue validators are effective

Hello there, It's common knowledge that using Vue-validator with most UI components can be challenging when it comes to validation. I've been utilizing Vue Material Components by @mjanys, which is a fantastic library. The author has included met ...

Encountering Issues with Formatting InnerHtml Text using RegEx

Technology: React.js I have been working on a custom function in JavaScript to highlight specific words within a code block. The function seems to be functioning correctly, but the highlighting isn't staying after the function is completed. Any ideas ...

Adding li elements dynamically, how can we now dynamically remove them using hyperlinks?

Please refrain from using jQuery code, as my main focus is on learning javascript. I am currently experimenting with adding li items dynamically to a ul when a button on the HTML page is clicked. Here's a sample implementation: HTML: <ul id="myL ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

Struggling to Enforce Restricted Imports in TypeScript Project Even After Setting baseUrl and resolve Configuration

I am facing challenges enforcing restricted imports in my TypeScript project using ESLint. The configuration seems to be causing issues for me. I have configured the baseUrl in my tsconfig.json file as "src" and attempted to use modules in my ESLint setup ...

Is there a way to trigger an Ajax function after individually selecting each checkbox in a list in MVC 4 using Razor syntax?

Is it possible to trigger an AJAX function when a checkbox within the ul below is checked? Each checkbox has a unique name attribute, such as chkbrand_1, chkbrand_2, chkbrand_3, etc. I am able to obtain the correct value using this code: $('.sear ...

Substitute "Basic Authentication" with "Form Authentication"

Is there a way in W20 to switch from using "Basic Authentication" to "Form Authentication"? The current documentation mentions only the use of "basicAuth" and does not provide information on implementing form authentication. Our app is built with Angular ...

Retrieve the content of the 'div' element, but exclude certain text

I have a task to copy the content from a div into a textarea, allow for editing within the textarea, and ensure that any changes made are saved back to the original div. I also need to filter out an attribute, such as data-bind: "some stuff;", set for the ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Resolving the Persistence Problem of Navigation Bar Fading In and Out

I've been struggling for hours trying different methods to achieve the desired outcome, but unfortunately, none of them have worked as expected. My goal is simple: I want the fixedbar to fade in when the scroll position exceeds the position of the ph ...

Ensure password confirmation is correct

Currently, I'm utilizing Yup for form validation. You can check it out here: https://www.npmjs.com/package/yup. Additionally, I came across this package called yup-password which seemed helpful for validating my Formik forms. Here's the link to i ...

Incorporate several websites into a React application without using iframes

After developing a React application with create-react-app, I attempted to embed another website onto the app using an iframe. Everything worked perfectly until I wanted to resize the iframe to fit the page, resulting in a Blocked a frame with origin from ...

Get a reference to pass as an injection into a child component using Vue js

Is there a way to pass a reference to child components? For example: The Parent component provides the ref: <template> <div ref="myRef" /> </template> <script> export default { name: 'SearchContainer', pr ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...

How do I access the content of a webpage once it has been generated using a template engine?

Currently, I am engaging in screen scraping for a website that heavily relies on JavaScript. The site utilizes a client-side templating engine to display all of its content. Initially, I attempted to use jQuery, which proved successful in the console but n ...

The Chrome Extension XHR always gets a 403 response except when it is triggered from the file:/// protocol

My current project involves the development of a Chrome Extension that relies on the fixer.io API for accessing currency exchange rates. To test this extension, I typically use a simple HTML page where I embed my JavaScript using <script> tags. When ...

Identify numbers and words within a sentence and store them in an array

Looking to split a string into an array based on type, extracting numbers and floats. The current code is able to extract some values but not complete. var arr = "this is a string 5.86 x10‘9/l 1.90 7.00" .match(/\d+\.\d+|\d+&bsol ...

Controller using the 'as' syntax fails to add new object to array

Lately, I've been experimenting with the Controller as syntax in Angular. However, I seem to be struggling to grasp its functionality. I am currently following a tutorial that utilizes $scope to bind the members of the controller function rather than ...

Simple Mobile-Friendly Tabs - mobile tabs are always visible

My JavaScript skills are not the best. I have been using Easy Responsive tabs and encountered an issue on the mobile version where clicking does not hide content, but only removes the "d_active" class and adds it to another element. I believe that if the ...