Search code examples
javascriptjqueryarrays

JS array is adding the first selected items value plus the new one with it


I have a bootstrap drown down that outputs data dynamically with values of 1-9.

Then I am attempting to grab the data of the selected dropdown item each time one is selected and push it to an array.

The issue is let's say the first selected item in the drop down has a value of 5, then the code I have now looks like this

enter image description here

when selecting a second option it then looks like this

enter image description here

why is it that it's adding the value of the first and the second option selected?

        var destinationVal = []

        $('.col-location .selectpicker').on('change', function () {
            var selectedVals = $(this).val();
            destinationVal.push(selectedVals)
            console.log(destinationVal)
}


Solution

  • If I understand your problem correctly When the event is firing, it's pushing the new value to the array destinationVal The second time you change the selection, you push the second value while keeping the first value in the array. you can save the selected value in a variable instead of an array. Or clearing the array before adding the new value.

    So it will be:

    var destinationVal
    
    $('.col-location .selectpicker').on('change', function () {
      var selectedVals = $(this).val();
      destinationVal = selectedVals;
      console.log(destinationVal)
    }