0

I created an API with Node.js express and mongodb, working perfectly fine.

I have a delete function that works fine as well.

I have an empty HTML select, and I generate the different options by a performing a get request that create all options that I have in my mongodb database.

I would like to delete the selected option in my select but I'm struggling to find a way to get the id of the specific select option.

HTML

<select id="content-dropdown">
  
</select>

JS :

 function showGames(url){
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (this.readyState == XMLHttpRequest.DONE && this.status == 200) {
            var response = JSON.parse(this.responseText);
            let i = 0;
            
            for(i in response){
              dropdown.innerHTML += '<option value="'+response[i].title+'" id="'+response[i]._id+'" class="game">'+response[i].title+'</option>';
            }
            
        }
    };
    request.open("GET", url);
    request.send();
  }

I managed to get all the id but when I use the delete function it delete the last option in the select.

I tried onchange / onclick event on the select but didn't manage to get it working.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Lyzix
  • 3
  • 2
  • Please show the code you are using to delete the option. Also note that using `for..in` over an array is [well, a bad idea](https://stackoverflow.com/q/500504/215552). – Heretic Monkey Oct 19 '20 at 17:28
  • Does this answer your question? [How do you get the currently selected – Heretic Monkey Oct 19 '20 at 17:30

1 Answers1

0

Just set the identifier as the option value: value="'response[i]._id'" then listen to the onchange event of the select element and retrieve the current value with event.target.value in order to call the backend.

Guerric P
  • 30,447
  • 6
  • 48
  • 86