-1

I have a select dropdown box with one option entered. I want to add additional options to the list using javascript or jquery. I have tried multiple ways but nothing works. Here is the html:

   <form class="form-all">
       <label for="selectStrategy" class="form-all" onChange="selectStrategy(this.value);">Select Strategy:</label><br>
       <select id="selectStrategy" width="400px" name="selectStrategy" margin-left="80px">
           <option value="new">New Strategy</option>
       </select><br><br>
    ...

Here is the javascript: Attempt #1

function loadStrategies(callback) {
    $.getJSON("http://localhost:8080/api/v1/strategies", function(data) {
        data.forEach(function (item) {
            console.log(item.name);
            var select = document.getElementById("selectStrategy");
            var option = document.createElement('option');                
            option.value = item.name;
            option.text= item.name;
            select.append(option);

Here is attempt #2

function loadStrategies(callback) {
    $.getJSON("http://localhost:8080/api/v1/strategies", function(data) {
        data.forEach(function (item) {
            console.log(item.name);
            var select = document.getElementById("selectStrategy");
            select.options[select.options.length] = new Option(item.name,item.name);

Here is attempt #3

function loadStrategies(callback) {
    $.getJSON("http://localhost:8080/api/v1/strategies", function(data) {
        data.forEach(function (item) {
            console.log(item.name);
            var select = document.getElementById("selectStrategy");
            var option = document.createElement('option');
            option.value = item.name;
            option.innerHTML = item.name;
            select.appendChild(option);

I have also tried option.text instead of option.innerHTML

Here is attempt #4

function loadStrategies(callback) {
    $.getJSON("http://localhost:8080/api/v1/strategies", function(data) {
        console.log("strategies getJSON data=", data);
        data.forEach(function (item) {
            console.log(item.name);
            var option = "<option value=" +item.name +">" +item.name +"</option>";
            $('#selectStrategy').append(option);

In all cases, nothing is added to the select list and no errors in the console. console.log(item.name) correctly shows the name that I want to put in the options. Suggestions?

EDIT Attempt #5

   function loadStrategies() {

    $.getJSON('http://localhost:8080/api/v1/strategies') 
        .then(data => {
        const $sel = $('#selectStrategy')
        data.forEach(({name})=> $sel.append(new Option(name, name)));  
        })
    }

Attempt #6

function loadStrategies(callback) {
    $.getJSON("http://localhost:8080/api/v1/strategies", function(data) {
        data.forEach(function (item) {
            console.log(item.name);
            let option = new Option();
            option.innerHTML = item.name;
            option.value = item.name;
            $('#selectStrategy').appendChild(option);
            let row = $('<tr class="clickable">');
            row.append($('<td class="left">').html(item.name));
            row.append($('<td>').html(item.version));
            row.append($('<td> class="right"').html(item.total_return));
            $('#strategy').append(row);
        });
    });
}

In the above example, I include more stuff that is in the same loop but adds rows to a table. It works just fine so why doesn't the part that adds items to a list work?:

$(document).ready(function () {
    loadWatchlist();
    loadStrategies();
user3217883
  • 1,216
  • 4
  • 38
  • 65
  • 1
    #4 has typo missing `<` in `+"/option>"`. Beyond that seems strange nothing is working. Can you provide minimal sample off data? Are you using any ` – charlietfl Dec 12 '20 at 20:06
  • That missing < might be the only problem. – react_or_angluar Dec 12 '20 at 20:15
  • There are two items in the json data. console.log correctly shows "sma-cross-and-extreme-hi-lo" and the next item correctly shows "sma-and-env_channel-crossover" – user3217883 Dec 12 '20 at 20:16
  • I fixed the missing < but same problem – user3217883 Dec 12 '20 at 20:17
  • 1
    Fine but if you provide as json we can run this. We shouldn't have to construct an array ourselves to test your code and make a [mcve] – charlietfl Dec 12 '20 at 20:17
  • The json is very long and wouldn't add any clarity to the issue. As long as item.name is correct, that should be all that matters. – user3217883 Dec 12 '20 at 20:19
  • Well if it's too much trouble for you to mock up a sample what do you expect from us? There is nothing obvious in what is shown so far – charlietfl Dec 12 '20 at 20:20
  • Change your question to reflect what this is all about now. And, read this https://json.org/example.html https://stackoverflow.com/questions/8292050/is-there-any-publicly-accessible-json-data-source-to-test-with-real-world-data https://opensource.adobe.com/Spry/samples/data_region/JSONDataSetSample.html – react_or_angluar Dec 12 '20 at 20:20
  • I'll try to figure out how to do that. Thanks for the links. – user3217883 Dec 12 '20 at 20:31
  • 1
    Very basic working example https://jsfiddle.net/gchvp1f0/1/ Something is missing from what you are showing us. Perhaps the ` – charlietfl Dec 12 '20 at 20:31
  • Wow, I'm amazed at how fast you did that! Thank you. I will try to rework my code based on your example. – user3217883 Dec 12 '20 at 20:34
  • I added your code as Attempt #5 but it didn't work either. Attempt #6 adds more details. – user3217883 Dec 13 '20 at 18:01

2 Answers2

0

This should work. At least it did for me :D

let select = document.getElementById('selectStrategy');
let option = new Option();
option.innerHTML = 'Another new strategy';
option.value = 'new-strategy';
select.appendChild(option);
  • Note that `new Option()` takes value and text arguments which cuts this down even more – charlietfl Dec 12 '20 at 20:37
  • @charlietfl oh okay, but wouldn't it just create an option object with just empty value and text values? And later add those values? Im not that good at javascript :D – Kristers Dzintars Dec 12 '20 at 20:43
  • Sure, just simpler to do it when you create it is all I was suggesting. Example https://jsfiddle.net/gchvp1f0/1/ – charlietfl Dec 12 '20 at 20:44
  • Yeah, you're right, it would just be two lines less in the code, thanks for the suggestion! – Kristers Dzintars Dec 12 '20 at 20:48
  • Thanks for your input. I've added it as Attempt #6. I also added more details in that function which adds items from the same json structure to a table. That part works fine. – user3217883 Dec 13 '20 at 18:02
0

if you want to add multiple options you must use loop

 $('#selectStrategy').append('<option value="'+item.name+'">'+item.name+'</option>');
Ruzaik Nazeer
  • 474
  • 2
  • 12
  • Thanks for you input. It is within a forEach loop. But what I hadn't been doing is including the double-quotes inside of the single quotes. Unfortunately, that didn't work either. Argggg! – user3217883 Dec 13 '20 at 22:40
  • I finally found the problem! I had another id in the code with the same id="selectStrategy". I changed this one to id="selectStrategy2" and it worked. I don't know if the double-quotes inside the single quotes also contributed to the solution but I will accept your answer. Thank you! – user3217883 Dec 13 '20 at 22:48