Add the AJAX response to the dropdown menu options

Currently in my project, I am utilizing Laravel as a backend. The scenario is such that once the corresponding page loads, it triggers an ajax request to fetch vehicle data which consists of vehicle model and plate number properties. My aim is to display these ajax response values in a select field. Despite using jQuery ajax for this task, I am encountering difficulty with appending the values to the select field. While there are no issues with the success response, I am puzzled about how to append these values to the select options.

Snippet from my HTML :

<div class="raw">
    <div class="form-group row" style="justify-content:center">
        <div class="col-sm-6">
            <label for="vehicleinfo">Select a Vehicle</label>
            <select class="custom-select form-control" id="select_list">         
                <option>- Select a Vehicle -</option>
            </select>
        </div>
    </div>
</div>

Piece of JS code utilized:

//?show vehicles
$(document).ready(function(){
$.ajax({
type: "GET",
url: '/get_vehicles',
})
.done(function(res) {
$.each(res, function(index, value) {
$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>');

let select_option = '';
select_option += "<option value='"+ value.vehiclemodel +"'>"+ value.platenumber +"</option>"; 
$('#selecet_list').append(select_option);
});
})
.fail(function(err) {
console.log(err);
});
});

The line

$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>');
successfully appends values to the div element but fails to do so for the select field.

Your assistance on resolving this issue would be greatly appreciated. Thank you.

Answer №1

If you want to insert <option> elements into an existing <select>, there are a few different methods you can use:

Using standard jQuery syntax

$.each(data, function (index, value) {
  $('#select_box').append($('<option/>', { 
      value: index,
      text : value 
  }));
});

Combining jQuery and vanilla JavaScript

$.each(data, function (index, value) {
  $("#select_box").append(new Option("Option Text", "Value"));
});

Answer №2

The ID of the HTML element has been set as select_list.

However, in your jQuery script, you are referring to an ID called selecet_list.

This inconsistency must be addressed for proper functionality.

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

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

Javascript splice method mistakenly eliminating the incorrect elements

I have an array of objects like the one below: [{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}] These objects are indexed as follows: [0, 1, 2]. I'm attempting to delete an item at a specific position using this code: $scope.selectedSound ...

How do I switch back and forth between displaying content as 'none' and 'block' using JQUERY?

Take a look at this code snippet. <div class="sweet-overlay" tabindex="-1" style="opacity: 1;display: none;"></div> Is there a way to switch the style attribute value from none to block and back? ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

angular corresponding vue binding="$props"

If I wanted to take a shortcut, I could utilize v-bind="$props" to dynamically set key values as shown in the sample below : <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> ...

Encountered a critical issue while attempting to execute the basic cloudinary sample, resulting in a

Seeking assistance with utilizing Cloudinary - I attempted their basic sample but came across the error detailed below. Fatal error: Cannot redeclare cl_upload_url() (previously declared in C:\My site\melbourne-apartment-bookings\admin&bsol ...

The tooltip in a scrollable container of Highcharts moves along with the content as it scrolls

I am currently facing an issue with my Highcharts instance that is displayed within a scrollable container. In addition, I have set the tooltip.outside option to true so that the tooltip always appears on top even if it exceeds the chart svg. The problem ...

Utilizing jQuery and AJAX to dynamically include multiple PHP pages

My webpage contains a div tag similar to this structure: <div class="ajax-load"> <!-- First.php: jquery-slider-1 jquery-widget-1 second.php: jquery-slider-2 jquery-widget-2 --> </div> There is also a ...

The Materialize accordion feature seems to be incompatible with the Algolia template

I'm currently facing an issue where the product description using Algolia in a Materialize accordion does not trigger when clicked. Below is the code snippet from my view: <div class="row"> <div id="hits-container"></div> ...

Adjust the hyperlink color of <a> to change when hovering over <tr>

When I hover over a <tr> tag, I want the color of the associated <a> element to change to white. I attempted to achieve this using jQuery in the following way: <script> $('tr').hover(function(){ $('a').cs ...

Revamping the vertices and UVs of DecalGeometry

I am currently experimenting with ThreeJS decals. I have successfully added a stunning decal to my sphere. Below is the code snippet I am using to place the decal on my sphere. (Please disregard any custom classes mentioned in the code.) // Creating the ...

React: segregate state and functions away from the view, although encountering an excess of props to transmit

Experimenting with a new approach that keeps state definition and functions separate from components. For example: // Display.js const Display = (props) => { const { data, setData, action } = props; ... return <div>...</div>; } // Di ...

The v-model in Vue does not function correctly when used with a single index within an array

I am encountering a situation with a series of input fields, including a checkbox and a dropdown button in each row. Additionally, there is a button to add a new row of inputs. When the checkbox is checked, it should disable the dropdown menu and make it ...

Having trouble with the Mysqli query not functioning properly in PHP code after being dispatched via Ajax

I am encountering a problem with a specific Myqsli query. $sqlselect = "SELECT visitatori_id FROM visitatori WHERE visitatori_nome='".$nome."' AND visitatori_cognome='".$cognome."' AND visitatori_orastart='".$time."' AND v ...

Error occurs when JSON.parse is used

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <script> var data = "{ 'name': 'John' }"; var result = JSON.parse(data); </script> ...

Arranging icons at the bottom of the post with a text box that changes dynamically

My challenge is that when the content in a box overflows, the box size increases and pushes the icons out of place. I want to ensure that the icons remain in a fixed position. This is how it currently looks: The comment, delete, and likes count end up on ...

Changing a background image url using jQuery by clicking a button

I'm struggling to find a way to use jQuery to add a background image URL to my CSS. Everything I've attempted so far has been unsuccessful. let button = document.querySelector('form button.btn') button.addEventListener('click&ap ...

What is the most efficient method for transforming JSON data into an object using JavaScript?

Currently, my method in JavaScript involves utilizing the eval function to transform JSON data retrieved from the server into an object. eval ("myObject="+data); I have received feedback that using eval is considered 'evil' and could potentiall ...

Preserve the values of checkboxes throughout the entire website by utilizing localStorage

Example A functionality in the example allows users to add images to a container by clicking on checkboxes. However, there is an issue where when a checkbox is checked on one page to store an image, and then another checkbox is checked on a different page ...