Assign a value to a Select option using JavaScript

Is there a way to populate the options in a <select> tag with values from an AJAX response array?

Here is my current code:

$.ajax({
    type: "GET",
    url: "http://.......api/1/AbsenceType",
    dataType: "json", 
    success: function (data) {
        // This part is not functioning correctly
        var ind = document.getElementById('mySelect').selectedIndex;
        document.getElementById('mySelect').options.value="2";//
    }
})

The select tag in question looks like this:

<select id=mySelect name="mySelect" required="required" data-mini ="true" onchange="myFunction3();"/>
    <option id ="type" value=""></option>
</select>

Answer №1

I have received an AJAX response array and I need to display it in a select tag.

Instead of directly putting the array into the select tag, you can add the options from the array to the select and set the selected value using this method:

Begin with an empty select element :

<select id="mySelect" name="mySelect">

</select>

Then, use the following function as a callback :

var callback = function (data) {

    // Get the select element
    var select = document.getElementById('mySelect');

    // Add options from the array
    for (var i in data) {
        $(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
    }

    // Set the selected value
    $(select).val(data[1]);
}

Check out the demo here :

http://jsfiddle.net/M52R9/

Also, refer to these links for more information :

  • Adding options to a select using jQuery/JavaScript
  • Set selected option of a select box.

Answer №2

give this a shot...

<select>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>`
</select>

$("select").val("3");

check out the live demonstration at: http://jsfiddle.net/y4B68/

appreciate it

Answer №3

Are you in search of something similar to this?

Check out the DEMO here

You have the option to add it like so -

$(function(){
$("#mySelect").html('<option value="2">2</option>');
});

I apologize for missing that you are actually doing this in an ajax callback. I have made updates in my demo as well.

You can also achieve this with -

document.getElementById("mySelect").innerHTML = '<option value="2">2</option>';

Instead of just adding a value, why not consider adding a new option altogether?

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

Ensure modifications to a variable are restricted within an if statement

I am struggling to find a way to globally change a variable within an if statement and ensure that the modifications persist. User input: !modify Bye var X = "Hello" if (msg.content.includes ('!modify')) { X = msg.content.replace('!modi ...

Capturing information from a modifiable table using Javascript

Creating an HTML Editable table with the property CONTENTEDITABLE, each TD has a unique ID (even though it's a long process and I only have basic JS knowledge) to keep track of the information inside. The table is wrapped by a form. At the end of the ...

Is there a JavaScript alternative to wget for downloading files from a specified url?

"wget http://www.example.com/file.doc" can be used to download the file to the local disk. Is there an equivalent way to achieve this in JavaScript? For example, let's look at the following HTML snippet. <html> <head> <script langu ...

Troubles with NextJS and TailwindCSS Styling

I encountered a strange issue when I used the component separately. Here's how the code looked like: <> <Head> <title>Staycation | Home</title> <meta name="viewport" content="initial- ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

stop an html page from opening a new window

When using my HTML-based application, there are instances when it needs to open another URL within an iframe. However, a problem arises when the third-party URL within the iframe also opens a new window with the same content and URL. How can I prevent th ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

Encoding multiple arrays with JSON and PHP is a powerful feature that allows

I'm working on encoding my multiple news array into JSON using PHP. Here's what my news array looks like: $news[1]["header"] = "First header"; $news[1]["content"] = "First news content"; $news[2]["header"] = "Second header"; $news[2]["content"] ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

There seems to be an issue with the visibility of the b-button within the b-table component in

I'm new to Vue Js and I'm having trouble with my b-button not displaying in my table. I can't figure out why. Below is my HTML code: <div id="listlocales"> <div class="overflow-auto"> ...

Retrieving PHP variable within a JavaScript file

I have a PHP script running on my server that tracks the number of files in a specific directory. I want to retrieve this file count ($fileCount) in my JavaScript code. numberOfImages.php: <?php $dir = "/my/directory/"; $fi = new FilesystemIterator($d ...

Implementing a Custom HTML Attribute to the Script Tag in Vue JS

I have decided to switch from using Google Analytics to Plausible analytics for my website. However, I am encountering an issue with adding the Plausible script to the head of my Nuxt JS document. I have created a custom plugin to handle this, but the Vue ...

Sharing Iframes across various Components within a Single Page Application (like Youtube)

Did you know that Youtube now lets you minimize the player while browsing the site? It's similar to the functionality on LolEsports.com with Twitch and embedded Youtube players. I'm interested in adding this feature to my own website. Here' ...

Sending a File Object and Data to an MVC 6 Controller in ASP.NET 5 using JavaScript

I have been working with an Ajax function that is supposed to handle file upload, but I am encountering some issues. Despite dragging and dropping the file, nothing seems to happen with the Ajax. Upon inspecting the properties on the page, I can see that t ...

Name of Document (changing from php to ?)

Greetings! Currently, I am utilizing PHP to include the document name as an example. folder/<?phpecho basename(__FILE__, '.' . pathinfo(__FILE__, PATHINFO_EXTENSION));?>_button.png I have observed that using PHP for this purpose and havin ...

Step-by-step guide on making a table of objects using JavaScript

As a new React user venturing into website creation, our goal is to design a table where each row outlines various details about an object. We aim to achieve rows similar to the example provided here. In my view, our strategy should involve generating a l ...

Jquery issue: Property or method is not supported by this object

Implementing a tree structure on my JSP Page using jQuery has been quite challenging. The tree structure necessitates the import of several jQuery files. However, upon running the JSP page, I encountered an error with the message "Object doesn't suppo ...

Exploring the power of Vuejs3 with Internationalization and the Composition API

Currently, I am working on a frontend interface in VueJS and integrating i18n with Vuejs 3. While the normal implementation of i18n works fine, I encountered issues when trying to use it with the composition API. In my main.js file, I have set up i18n as ...

glsify - encountering the error message 'This file type could require a specific loader to be handled'?

Currently, I'm attempting to implement a custom shader following the guidance provided at https://tympanus.net/codrops/2019/01/17/interactive-particles-with-three-js/. I have imported the .frag and .vert files (provided in the link) and replicated the ...

Why does jQuery function properly in jsfiddle, but not in an HTML file?

I have been troubleshooting repeatedly, but I am unable to figure out why the jQuery code is not functioning as expected. Strangely enough, it works perfectly in jsfiddle! Here is the HTML code: <!doctype html> <html> <head> <meta ch ...