NicolaHearn
NicolaHearn

Reputation: 49

jquery Populating HTML select with options and setting a default results in default showing blank

I am using this jquery code below to put a list of countries into a select option and set the user's country as the default.

If I console log, the code shows I am recognising the user country correctly and in my project it has a blank where "United Kingdom" should be and that option is selected, it is just blank.

Why is this and what I should try doing differently?

  const sortedData = result.data.sort();
  for (var i = 0; i < sortedData.length; i++) {
    if (sortedData[i] === userCountry) {
      $("#country-selector").append(
        $("<option selected>", {
          value: sortedData[i],
          text: sortedData[i],
        })
      );
    } else {
      $("#country-selector").append(
        $("<option>", {
          value: sortedData[i],
          text: sortedData[i],
        })
      );
    }
  }
};```

Upvotes: 2

Views: 29

Answers (2)

fdomn-m
fdomn-m

Reputation: 28621

There's no overload to mix passing in an HTML snippet and apply additional attributes to that snippet.

Pick one or the other

  • an HTML string (with attributes in the string)
    or
  • an element name with attributes as the second parameter

According to jquery you can create DOM nodes using two methods (using $(..) at least):

jQuery(html [,ownerDocument])
html
A string of HTML to create on the fly

jQuery(html, attributes)
html
A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).
attributes
An object of attributes, events and methods to call on the newly-created element

When you use $("<option selected>", attrs) the first argument is not a "single, standalone element" so jquery uses the first overload, passing your attributes as "ownerDocument" (which then gets ignored as it's the wrong type).

Upvotes: 0

C3roe
C3roe

Reputation: 96417

Passing the selected attribute in the element HTML code to parse, appears to interfere with the setting of the attributes passed via parameters. Set the selected via the parameters as well instead, as true or false:

for (var i = 0; i < sortedData.length; i++) {
  $("#country-selector").append(
    $("<option>", {
      value: sortedData[i],
      text: sortedData[i],
      selected: sortedData[i] === userCountry // value of that comparison expression
                                              // will be either true or false
    })
  );
}

Upvotes: 0

Related Questions