Topic: Dynamic select and select options breaking styling
Arnt Oddvar Pedersen
pro priority vip early access premium asked 5 months ago
Expected behavior
Creating a select element should be styled
Actual behavior
No styling applied to select element
Resources (screenshots, code snippets etc.)
I'm adding some select options dynamically using Sweetalert2.
import Swal from 'sweetalert2';
Swal.fire({
title: 'my title',
html: '
<select class="select" id="mySelectElement">
<option value="1">One</option>
<option value="2">Two</option>
</select>
<label class="form-label select-label">Example label</label>
',
didOpen: () => {
$('#mySelectElement').append(`
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
`);
},
});
This issue is sort of two-fold. Dynamically adding a select element makes it appear as unstyled. (Default browser styles) And if you dynamically add options to the element, the select element itself stops working. (You can't select an option).
Is there a workaround for this, or is this the expected behaviour? Other input outlines and styles is easy enough to update through the .update() or .init() function.
Arkadiusz Idzikowski
staff answered 5 months ago
When you add the component template dynamically it won't be initialized automatically via select class. In this case, you would need to initialize it manually with a new keyword as explained in the documentation (API section):
https://mdbootstrap.com/docs/standard/forms/select/#api-section-usage
We will consider adding a public init method because it can be useful for similar use cases.
Arnt Oddvar Pedersen pro priority vip early access premium commented 5 months ago
Hmm. I thought I already tried adding it through the constructor! I'll give it a go and post back if there is any issues. Thank you!
Arnt Oddvar Pedersen pro priority vip early access premium commented 5 months ago
@Arkadiusz Idzikowski Tried adding the Select element dynamically, however it doesn't seem to listen to methods, or the dropdown object is gone: https://i.imgur.com/FV3zS1w.png
Added the select html to the rendered template, and initializing it. Renders it properly, looks fine, but the dropdown is gone as you can see in the picture linked.
Arkadiusz Idzikowski staff commented 5 months ago
@Arnt Oddvar Pedersen Could you paste the full HTML/JS to the first post, so we can reproduce this problem on our end?
Are there any errors in the console when you initialize the component or try to open the dropdown?
Answered
- User: Pro
- Premium support: Yes
- Technology: MDB 5
- MDB Version: 2.0.0
- Device: N/A
- Browser: N/A
- OS: N/A
- Provided sample code: No
- Provided link: No