Topic: unable to set selected option in material select with optgroups

dschace free asked 4 years ago


Expected behavior

I have a relatively simple form containing a dropdown selection with options grouped within optgroups. The form its self renders without issue and dropdown works as expected through normal manual interaction. When the user selects a button on the page, the a new row of form fields will appear so that they can input additional information. After much digging, I learned the only way to make this work properly when using mdb select fields is by

$(".mdb-select").materialSelect({ destroy: true });

and then reinitializing after the new row of fields has been rendered through something like

$('.mdb-select').materialSelect();

This also works as expected BUT... here is my first problem:

Problem 1: You loose all the form data you already selected from dropdowns when you do a tear down

After several more hours, I gave up trying to find a way a way to specifically tear down and initialize certain fields because it simply would not work. It seems to only work as an all or nothing. I have tried adding classes to the new fields so that I could just initialize them... no luck. All or nothing is all that would work.

My next approach was to go through with the tear down, reinitialize AND then just refill the previously fill form fields using jquery.

Problem 2: No solution presented online seems capable of changing the optgroup fields using jquery when it is material select optgroup. I have even tried doing this on a generic optgroup without material select classes and it works. Does someone... anyone have a solution to either or both of problems?

Here is the mdb styled optgroup rendering as expected

And here is a link to the snippet: https://mdbootstrap.com/snippets/jquery/dschace/877715

Someone please help with either being able to change the selected value using javascript OR a solution in which I can initialize another dropdown field without messing this one up. Note: if you try initialize a second time, it causes the original dropdowns to duplicate.


Krzysztof Wilk staff answered 4 years ago


Hello!

You should initialize particular select using id. You can see how it works in those snippets: https://mdbootstrap.com/snippets/jquery/krzysztof-wilk/883593

https://mdbootstrap.com/snippets/jquery/s-kaczmarek/883560



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB jQuery
  • MDB Version: 4.8.2
  • Device: MacBook Pro
  • Browser: Chrome
  • OS: MacOS Mojave
  • Provided sample code: No
  • Provided link: Yes