Reputation: 143
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:
Heres how it looks when you close it:
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
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
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
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
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