jeevan kumar
jeevan kumar

Reputation: 156

How to handle multiple dropdown select option in vanilla JS

Given the following select node:

<select multiple="multiple">
     <option value="car">car</option>
     <option value="scooter">scooter</option>
     <option value="bus">bus</option>
</select>

How can I do multi-select without pressing the ctrl key and without using jQuery ? I would like to achieve this using only vanilla Javascript. Thanks!

Upvotes: 1

Views: 4878

Answers (2)

Asons
Asons

Reputation: 87262

Here is one way to do that...

(function(values,sel) {

  var sel = document.querySelector('select');
  values = new Array(sel.length);

  sel.addEventListener('click', function(e) {
    
    values[e.target.index] = !values[e.target.index];    
    for(var i=0;i<values.length;++i) {
      sel.options[i].selected = values[i];
    }

  });

})();
<select multiple="multiple">
     <option value="car">car</option>
     <option value="scooter">scooter</option>
     <option value="bus">bus</option>
</select>

...and a non script way could be with checkbox's

.check-multiple {
  display: inline-block;
  height: 60px;
  overflow-y: scroll;
  border: 1px solid gray;
}
.check-multiple input {
  display: none;
}
.check-multiple label {
  display: block;
}
.check-multiple span {
  display: inline-block;
  width: 100%;
}
.check-multiple input:checked ~ span {
  background: #03f;
  color: white;
}
<div class="check-multiple">
     <label><input value="car" type="checkbox"><span>car</span></label>
     <label><input value="scooter" type="checkbox"><span>scooter</span></label>
     <label><input value="bus" type="checkbox"><span>bus</span></label>  
</div>

Upvotes: 3

Alex Johnson
Alex Johnson

Reputation: 1574

I would recommend using checkboxes. Those are the best HTML element to support selecting multiple options.

You could write your own multi-select component in Javascript to mirror popular libraries such as Chosen, but I wouldn't recommend it due to the time committment.

Upvotes: 1

Related Questions