Materialize: Programatically set values on select

Created on 29 Jan 2018  路  4Comments  路  Source: Dogfalo/materialize

Expected Behavior


It would be extremely handy to be able to do something along the lines of

const select = M.Select.init(el, options);
select.setValue('value'); // for single selects
select.setValue(['value1', 'value2']); // for multiselect

Current Behavior


For as far as I can see there's no method available that does this.

Possible Solution



Maybe it's interesting to implement this in the Dropdown component and then the Select component can simply forward it's calls to setValue to the dropdown.

Context



I came across this problem when trying to implement a wrapper in Angular for Materialize.
In Angular for proper form integration you need to be able to set the value programatically at some point when a component wants to update it, which is currently not possible.

Your Environment


  • Version used:
  • Browser Name and version: 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
  • Operating System and version (desktop or mobile): Windows 10 x64 (desktop)

All 4 comments

You can programmatically change the original select element, and then reinit the select plugin

What do you mean by reinit?

You can just init the plugin again, the same as always. All our plugins are built so that if you init a plugin multiple times, it will destroy the existing instance of the plugin and reinitialize the plugin.

const setMaterializeFormSelectValue = (id, value) => {
  $(id).parent().find('.dropdown-content > li.selected').removeClass('selected').removeClass('active')
  let liArr = $(id).parent().find('.dropdown-content > li')
  let opArr = $(id).find('option')
  // assumption: both arrays have the same index order
  let text = '?'
  opArr.each((i, op) => {
    if ($(op).attr('value') === value) {
      $(liArr[i]).addClass('selected').addClass('active')
      text = $(liArr[i]).text()
    }
  })
  // also apply the new text
  $(id).parent().find('input[type=text]').val(text)
  // also update thew hidden select
  $(id).val(value)
}
setMaterializeFormSelectValue('#mySelect', 'some-option-value')
Was this page helpful?
0 / 5 - 0 ratings

Related issues

hartwork picture hartwork  路  3Comments

bradley-varol picture bradley-varol  路  3Comments

djensen47 picture djensen47  路  3Comments

cope picture cope  路  3Comments

artur99 picture artur99  路  3Comments