When dynamically adding an option, the select value becomes empty

I am facing a problem with a select element that I cannot change programmatically. Initially, the select has only one option:

The initial HTML structure looks like this:

<select id="clients" name="client">
    <option>Existing Clients...</option>
</select>

After fetching clients through an AJAX request, I add them dynamically to the select:

getClients();

function getClients() {
  $.get('ajax/get-clients.php')
    .done(function(response) {
      for (let client of JSON.parse(response)) {
        addClientOption(client.id, client.company_name);
      }
    })
    .fail(function(response) {
      console.log(response);
    });
}

function addClientOption(id, name) {
  let newOption = document.createElement('option');

  newOption.value = parseInt(id);
  newOption.text = name;
  document.getElementById('clients').appendChild(newOption);
}

Now the select contains multiple options:

<select id="clients" name="client">
  <option>Existing Clients...</option>
  <option value="6">Number1</option>
  <option value="77">SecondROUND</option>
  <option value="14">Whips Dat Llama</option>
</select>

I then try to change its selected value using JavaScript:

console.log(document.getElementById('clients').value); // => "Existing Clients..."
document.getElementById('clients').value = 6;          // expecting "Number1"
console.log(document.getElementById('clients').value); // => ""

// The select element still displays the "Existing Clients..." option.

Even after trying hard-coding the options directly into the select, it works as expected. The issue seems to be specific to dynamically adding options. While I can find a workaround, I would appreciate an explanation for why this behavior is happening.

Answer №1

Using AJAX to load options asynchronously requires waiting for the response before assigning values. The .value must be set within the getClients callback function to ensure the option with that value exists.

function getClients() {
  $.get('ajax/get-clients.php')
    .done(function(response) {
      for (let client of JSON.parse(response)) {
        addClientOption(client.id, client.company_name);
      }
      document.getElementById('clients').value = 6;
    })
    .fail(function(response) {
      console.log(response);
    });
  }

Answer №2

Setting the value of the <select> field is optional, but it's important to use the attribute selected with the option field you wish to choose.

For more information, visit this link

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 JQuery video player's full screen toggle feature is not correctly assigning the class name

I've been tackling a bug in my JavaScript/jQuery video player that has left me stumped. One of the key features of this player is an enter/exit full-screen button located at the bottom of the HTML snippet: (function($) { /* Helper functions */ ...

Issue with Bootstrap 4.2 modal: Unable to edit input fields, button cannot be clicked, modal does not close

https://i.sstatic.net/vHnVG.png https://i.sstatic.net/MhU3f.png Utilizing Bootstrap 4.2.1, I have a modal that opens via a specific link: <a href="#" data-toggle="modal" data-target="#inviteByEmailPopup" data-backdrop="false" data-keyboard="false"> ...

Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Od ...

Prevent unnecessary clicks with Vue.js

In my vue.js application, there is a feature to remove items. The following code snippet shows the div element: <div class="ride-delete" @click="delete"> <p>Delete</p> </div> This is the function used to handle the click ...

Using the if else and hasClass statements for validations in Cypress testing

I am struggling to validate the titles for a certain component. Here is my specific Cypress code snippet: it('Confirming the correctness of all tile titles', () => { cy.get('.bms-scoreboard__game-tile') .each(($el) => { ...

Assign the DatePicker Object to an HTML Element

I am currently using a SyncFusion date picker in my project and the implementation looks like this: var datepicker = null; $("#datepicker").hide(); $("#click").click(function(){ $("#datepicker").show(); datepicker = new ej.calendars.DatePi ...

The use of `preventDefault()` in React for the `onCopy` event is ineffective

I'm currently exploring ways to prevent the clipboard events from copying text when the onCopy event is triggered. I've tried using the onCopy handler and e.preventDefault() method, but the text is still being copied without any issues. What am I ...

MUI: Interaction with a button inside a MenuItem when not interacted with MenuItem itself?

Currently, I am utilizing MUI's Menu / MenuItem to create a menu of missions / tasks similar to the screenshot below: The MenuItem is interactive: // ... other code <MenuItem value={mission.issueIdentifierId} sx={{px: ...

Utilize JavaScript to identify the orientation of an iPad device

I have implemented the code below to monitor the orientation of the iPad. However, it seems that this method is only triggered when I physically rotate the device or change its orientation. If the app is launched in landscape mode and I navigate to a dif ...

Having trouble getting a form to submit to a Rails server using AJAX in IE11 with jQuery

Currently, I'm attempting to transfer data from a form to a Rails server using AJAX. The form consists of two text inputs and one file input. Below is the code for my submit event handler: $("form").on("submit", function(event) { event.preventDefa ...

Is there a way to trigger the onclick event while dragging the div?

Exploring a Div: <div id="up" onmousedown="handleMouseDown('url(/scanToUserBox/img/cpt_subfunc_005_prev_p.png)', this)" onclick="changePage('up')"> </div> Upon clicking the div, the onmousedown event is trig ...

Adjust CSS classes as user scrolls using skrollr

I am currently facing an issue with the prinzhorn/skrollr plugin when trying to use removeClass/addClass on scroll function. I have attempted to find a solution but unfortunately, nothing has worked for me. <li class="tab col s3"><a data-800="@cl ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

Using jQuery to replace the content of a div with a delay?

I am attempting to utilize jQuery to create a fade effect on an element, replace its innerHTML content, and then fade it back in once the new content has been added. I have successfully managed to replace the element's content using the .html() method ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

babel-minify or terser over uglify-js

Exploring ES6+ (modern JavaScript) is a new adventure for me, and I've discovered that in order to use it in browsers, tools like babel-minify or terser are necessary. It's interesting to note that Babili was initially thought to be a separate to ...

Exploring document in Node.js

Is there a way to read the data of a file (for example, read.txt) in Node.js without buffering the data? I want to access the content of the file directly rather than as buffered data. Also, how can I delete a folder in Node.js? ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

Having trouble scrolling to the top in Flickr Search using AngularJS, the results are restricting my movement

I recently followed a tutorial on creating a Flickr Search App with AngularJS (https://www.youtube.com/watch?v=lvGAgul5QT4). I managed to show the search results on my page, but encountered an issue: I couldn't scroll all the way back up to the search ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...