1

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!

6
  • 1
    What have you tried so far? This sounds like a task better use for radio buttons than a select. Commented Mar 28, 2016 at 13:04
  • 1
    problem here is the fact not all browsers support click on options so to make it work it would be a mess. Maybe you should use a group of checkboxes and style them to look like a select? Commented Mar 28, 2016 at 14:05
  • @AdamKonieska Can't use radio as they can't do multiple select .. so I'm sure you meant checkbox Commented Mar 28, 2016 at 14:15
  • @LGSon definitely. Commented Mar 28, 2016 at 14:19
  • I updated my answer with a checkbox variant as well Commented Mar 29, 2016 at 7:13

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.