I am trying to implement a Select All option for Materialize Select Multiple within the Select input. The second solution in this question is supposed to fit quite well, but after pasting the code into my file, it would not work at all, as if the JS code wasn't there.
This is my attempt to make the above solution work
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
// $('select').val([1]);
$('select').formSelect();
$('select.select_all').siblings('ul').prepend('<li id=sm_select_all><span>Select All</span></li>');
$('li#sm_select_all').on('click', function () {
var jq_elem = $(this),
jq_elem_span = jq_elem.find('span'),
select_all = jq_elem_span.text() == 'Select All',
set_text = select_all ? 'Select None' : 'Select All';
jq_elem_span.text(set_text);
jq_elem.siblings('li').filter(function() {
return $(this).find('input').prop('checked') != select_all;
}).click();
});
})
</script>
</head>
<div class = "row">
<label>Materialize Select</label>
<select class="select_all" multiple >
<option value="" disabled selected>Choose your option</option>
<option value = "1">Mango</option>
<option value = "24">Orange</option>
<option value = "3">Apple</option>
<option value = "4">Cucumber</option>
<option value = "5">Litchi</option>
</select>
</div>
<script>M.AutoInit();</script>
Does anyone know of a way to implement this feature or any other possible alternatives, apart from having a separate button? Thank you.
You can always manually select all the options very easily using jQuery:
$('.select-wrapper .dropdown-content li').trigger('click');
Materialize select is actually just a dropdown (UL > LI) triggered by a text input.
But, thinking about UX, you might want to tie this is with the optgroup
, so that the user has the option to toggle these on an off. it's not perfect, as we don't have a placeholder to begin with, but this example could be modified.
<select multiple>
<optgroup label="Select All">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</optgroup>
</select>
<label>Select All Example</label>
And the jQuery, that listens for a click on the li.optgroup
:
$('li.optgroup').on('click', function(){
$('li.optgroup-option').trigger('click');
});