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.
igor_g
June 18, 2019, 8:06pm
2
Use DOM Model instead of html string creating. That means to create option element and to add it to options collection of select.
igor_g
June 18, 2019, 8:11pm
4
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
.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>
igor_g
June 18, 2019, 10:10pm
7
Not completelly…
listItems.push ($('<option>', { value : value.reportID})
Yes I did spot that
Thanks for the confirmation it still seems to work with or without.
Though best do things properly
Having another issue now with the second dropdown
I’ll post back if I cant fix it.
Barry
system
Closed
September 18, 2019, 5:15am
9
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.