Search code examples
javascriptapiselected

Javascript delete function from a select


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.


Solution

  • 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.