Topic: Floating labels overlap values in dynamically inserted forms

itsolutions free asked 4 weeks ago


A settings form is inserted after an API response. Its labels stay over the saved values until focus changes.

How should I initialize the outline wrappers after insertion?


Igor Przybysz staff answered 3 weeks ago


Yes. querySelectorAll returns a static collection, so outlines still contains the wrappers from the discarded form. Query the replacement elements after assigning innerHTML, and set their values before initializing them. That gives each visible field an instance attached to its actual wrapper.

const response = await fetch('/settings/form');
panel.innerHTML = await response.text();
panel.querySelector('#displayName').value = settings.displayName;
panel.querySelectorAll('.form-outline').forEach(wrapper => {
  Input.getOrCreateInstance(wrapper);
});

Igor Przybysz staff answered 3 weeks ago


Apply the saved values before initializing the newly inserted .form-outline wrappers. Initializing an earlier set of elements, then replacing their HTML, leaves the replacement fields without the corresponding component instances. Select the wrappers from the inserted form, not from a cached list created before the API response.

Also check for duplicate input IDs and mismatched label targets. If the form starts inside a hidden container, please include when it becomes visible, together with the value-assignment and initialization code. That will let us distinguish stale elements from an outline layout issue.

https://mdbootstrap.com/docs/standard/forms/input-fields/


itsolutions free commented 3 weeks ago

The form is already visible when the response arrives. I noticed that I collect the outline elements before replacing the panel contents. This is the relevant part; settings contains the values returned by our API. Could that explain why focusing each field fixes its label?

const outlines = panel.querySelectorAll('.form-outline');
const response = await fetch('/settings/form');
panel.innerHTML = await response.text();
panel.querySelector('#displayName').value = settings.displayName;
outlines.forEach(wrapper => Input.getOrCreateInstance(wrapper));


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 Standard
  • MDB Version: MDB5 9.2.0
  • Device: Desktop
  • Browser: Firefox
  • OS: Windows 11
  • Provided sample code: No
  • Provided link: No