Search code examples
javascriptjqueryarraysecmascript-6dropdown

Return selected values on change and not repeat on un-select


How to always return selected options in an array. On change return new array of selected elements.

let yo = [];
$(`#filter`).on('change', function() {
   $('option:selected', this).each(function() {
        // console.log(this.value);
        yo.push(this.value);
   });
});
console.log(yo);

Right now this returns:

on first select my result is: ['one']. On 2nd select, I get: ['one', 'two']. On two unselect, my result is ['one', 'two', 'one']. On two unselected how can I make my result be ['one']?

On every change, can I just get back the selected elements?


Solution

  • You just need to reset the yo array inside the function. At the moment, the array is only declared once, and then you keep pushing to it.

    $(`#filter`).on('change', function() {
       yo = [];
       $('option:selected', this).each(function() {
            // console.log(this.value);
            yo.push(this.value);
       });
    });
    

    This should work proerly, every time the on change function runs, it will reset the array before pushing to it again.