How to make a listbox where I can select more than one value?

3

I want to make a listbox, where the user can select several options, but using the select multiple, I have to hold ctrl, but this is not ideal, many people will not know that. Can anyone help?

<div class="form-group">                
              <label> Dias disponíveis <br />
                <select name="dias" id="dias" multiple>
                  <option value="Segunda-Feira">Segunda-Feira</option>
                  <option value="Terça-Feira">Terça-Feira</option>
                  <option value="Quarta-Feira">Quarta-Feira</option>
                  <option value="Quinta-Feira">Quinta-Feira</option>
                  <option value="Sexta-Feira">Sexta-Feira</option>
                </select>
              </label>
</div>
    
asked by anonymous 07.09.2017 / 05:19

2 answers

2

Select2 is an appropriate plugin for this if I want something a bit more elegant. Just download and put the css in the header and the javascript files at the bottom of the page, before the end of the </body> tag.

$('.multiplo').select2({
  placeholder: 'selecione'
});
.multiplo{
width:50%;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.css" rel="stylesheet"/>

<select class="multiplo" name="" multiple="multiple">
  <option>Um</option>
  <option>Dois</option>
  <option>Três</option>
  <option>Quatro</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/i18n/pt-BR.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.js"></script>
    
30.10.2017 / 21:08
2

You can change the default behavior of it, using just Javascript, without JQuery could do:

let elemento_options = document.querySelectorAll('select[multiple] option');

elemento_options.forEach(function(elemento, index) {
  elemento.addEventListener("mousedown", option_handler)
});

function option_handler(e) {
  e.preventDefault();
  e.target.selected = !e.target.selected;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label>Diasdisponíveis<br><selectname="dias" id="dias" multiple>
    <option value="Segunda-Feira">Segunda-Feira</option>
    <option value="Terça-Feira">Terça-Feira</option>
    <option value="Quarta-Feira">Quarta-Feira</option>
    <option value="Quinta-Feira">Quinta-Feira</option>
    <option value="Sexta-Feira">Sexta-Feira</option>
  </select>
</label>

This will cause when clicked (using mousedown , which the same as the browser uses) will prevent the default behavior and will reverse the current value, so if it is already marked it will uncheck.

    
07.09.2017 / 06:18