[Solved] Javascript select removes static <option> when fired

Hi all

I’m currently populating a number of (<select>) elements from an object literal works ok.

Below is the select element before any JS is fired:

<select id="first">
	<option selected value="-1">Select</option>
</select>

After the JS is fired

<select id="first">
	<option selected value="1">Name 1</option>
    <option value="2">Name 2</option>
    <option value="3">Name 3</option>
...
</select>

As you can see, the selected label is removed when the JS is fired.

How do I fix it so it works and looks like:

<select id="first">
    <option selected value="-1">Select</option>
	<option value="1">Name 1</option>
    <option value="2">Name 2</option>
    <option value="3">Name 3</option>
</select>

I can’t trigger the first option?
I want to keep the label selected first to instruct the user.

JS
#first

$(function() {
  "use strict";

  var listItems= "";
  for (var i = 0; i < reportList.reportTable.length; i++){
    listItems+= "<option value='" + reportList.reportTable[i].reportID + "'>" + reportList.reportTable[i].name + "</option>";
  }
  $("#first").html(listItems);
});

Any advice thanks.

Use DOM Model instead of html string creating. That means to create option element and to add it to options collection of select.

Thanks @igor_g

Small example maybe?

Barry

https://api.jquery.com/append/

I have the below snippet.
I think this could be the answer.

//make option list separately and append to select id
  var listItems = [];
  $.each(reportList.reportTable, function(key, value) {
      listItems.push ($('<option>', { value : key })
            .text(value));
  });
  $('#first').append(listItems);

Not sure how to fit this together with my current code?
Now I see:

<select id="first">
<option selected="" value="-1">Select</option>
<option value="0">[object Object]</option>
<option value="1">[object Object]</option>
<option value="2">[object Object]</option>
...
</select>

Any pointers?
Thanks.

Fixed it :smiley: :upside_down_face:

.text(value.name)

<select id="first">
  <option selected="" value="-1">Select</option>
  <option value="0">Name 1</option>
  <option value="1">Name 2</option>
  <option value="2">Name 3</option>
</select>

Not completelly…

 listItems.push ($('<option>', { value : value.reportID})

Yes I did spot that :nerd_face:
Thanks for the confirmation it still seems to work with or without.
Though best do things properly :slightly_smiling_face:

Having another issue now with the second dropdown :thinking:

I’ll post back if I cant fix it.

Barry