Rockernaap
Rockernaap

Reputation: 143

Materialize Multiple Select

I have a Materialize Multiple Select element. But I can't seem to find a way to retrieve the selected values. Does anybody know how you can retrieve the selected values?

Here's the look when you select it: Multiple Select active

Heres how it looks when you close it: Multiple Select inactive

But the question is how to retrieve the values inside the selector when closed.

EDIT: I am using Materialize CSS (http://materializecss.com)

Upvotes: 5

Views: 8138

Answers (4)

Josías Genem
Josías Genem

Reputation: 33

For people searching for a Vanilla Javascript solution, you have to use a Materialize element instance, and then call its method getSelectedValues().

Here is the Materialize site example:

var instance = M.FormSelect.getInstance(elem);
instance.getSelectedValues(); // You will get an array with all the selected options.

Here is the source: https://materializecss.com/select.html

Upvotes: 0

Jamshaid
Jamshaid

Reputation: 57

Please try this out: Here you shall find an appropriate way of retrieving and removing values from the multiple select. Actually materialize uses UL and LI to desplay a select. That is why it creates errors.

$(document).ready(function () {
    $('select').material_select();
    $('select').change(function(){
        var newValuesArr = [],
        select = $(this),
        ul = select.prev();
        ul.children('li').toArray().forEach(function (li, i) {
            if ($(li).hasClass('active')) {
                newValuesArr.push(select.children('option').toArray()[i].value);
            }
        });
        select.val(newValuesArr);

        console.log($(this).val());
    });
});

http://jsfiddle.net/9bL25jw9/59/

Upvotes: 1

vanthinh129
vanthinh129

Reputation: 1

Try it (get more select tag)

var datas = {};// object name=> value
$("form").find("select.initialized").each(function() {
    var value_input_select = $(this).parents(".select-wrapper").find("input.select-dropdown").val()
    value_input_select = value_input_select.replace(/ /gi,"").replace(/ /gi,"")
    var value_input_select_array = value_input_select.split(",")
    var value_string = ""
    $(this).find("option").each(function(){
      if(value_input_select_array.indexOf($(this).text().replace(/ /gi,"").replace(/ /gi,"")) >= 0){
        value_string += $(this).attr("value")+","
      }
    })
    if(value_string != ""){
      value_string = value_string.substring(0, value_string.length-1)
    }
    datas[this.name] = value_string;
  });

Upvotes: 0

kielni
kielni

Reputation: 4989

You can get it with basic jQuery; there's nothing special about the Material markup.

For a select like this:

<select id="mySelect" multiple>
    <option value="1" selected>Option 1</option>
    <option value="2" selected>Option 2</option>
    <option value="2">Option 2</option>
</select>

$('#mySelect').val() will return an array of selected values: ["1", "2"]

Upvotes: 7

Related Questions