Gabriel Rogath
Gabriel Rogath

Reputation: 834

How to manage order of select options on event change

I am trying to get items when selected by user to an array with onchange action, The problem is when user select lower option according to the arrangement it does not record the higher options when selected, but rather it retain the value of the lower option untill you select an lower option if it exists.

<select name="tasks[]" id="activities" multiple="multiple" onchange="getSeleted()">
  <option value="1">lifting</option>
  <option value="2">jogging</option>
  <option value="3">sleeping</option>
  <option value="4">working</option>
  <option value="5">praying</option>
</select>

</script>

 var myarr = [];
 function getSeleted(){
    var activityValue =document.getElementById('activities').value;
    myarr.push(activityValue);
    console.log(myarr);   
  }

</script>

Whenever I select lower option it stuck with that option untill you select another lower. e.g if you select option 1, and then 2, and then 3 the console prints.

//1,2 and 3  
console ['1',]
console ['1','1']
console ['1','1','1']
//3,2 and 1   
console ['3',]
console ['3','2']
console ['3','2','1']
//3,4 and 4   
console ['3']
console ['3','3']
console ['3','3','3']
 //5,2 and 4   
console ['5']
console ['5','2']
console ['5','2','2']

It acts the same even with string, Why does it behave like this, and how can I handle it.

Upvotes: 2

Views: 47

Answers (1)

4b0
4b0

Reputation: 22323

Why not make things little bit easier with filter and map.

Example:

function getSeleted() {
  var select = document.getElementById('activities');
  var selected = [...select.options]
    .filter(option => option.selected)
    .map(option => option.value);
  console.log(selected);
}
<select name="tasks[]" id="activities" multiple="multiple" onchange="getSeleted()">
  <option value="1">lifting</option>
  <option value="2">jogging</option>
  <option value="3">sleeping</option>
  <option value="4">working</option>
  <option value="5">praying</option>
</select>

Upvotes: 1

Related Questions