19

Normally, with Materialize, the labels for text input boxes show up inside the input boxes until a user enter selects the box and enters text in it. However, when a box's value is filled via javascript, the label does not move out of the way. It stays in the box and overlaps with the text entered. Is there a way to trigger the label transition with javascript as well, so this doesn't happen?

neurodynamic
  • 4,294
  • 3
  • 28
  • 39

8 Answers8

32

More specifically, if you are using Materialize in Rails with turbolinks enabled, you will find that Materialize form fields which are prefilled with non-empty values are not active on page load.

The following method worked for me:

$(function() {
    M.updateTextFields();
});

It will add class 'active' to both corresponding labels and prefix icons.

elquimista
  • 2,181
  • 2
  • 23
  • 32
16

The label transition behavior is triggered by adding the active class to the label's element. Thus, if you make your javascript add that class to the label (e.g. $('label').addClass('active')) in addition to filling in the field, the label will transition out of the field just as it would when selected by a user action.

neurodynamic
  • 4,294
  • 3
  • 28
  • 39
3

If you use labels, you will use:

$("label[for='idTag']").addClass('active');
jrswgtr
  • 2,287
  • 8
  • 23
  • 49
Eduardo Tolentino
  • 1,470
  • 1
  • 12
  • 8
2

The document.ready event only fire once when turbolinks is working, so instead you need to tap into the turbolinks load event.

It happens so fast that if you want to see the animation, wrap it in a tiny timeout.

With timeout/visible animation

document.addEventListener('turbolinks:load', () => {
    setTimeout(() => {
        M.updateTextFields();
    }, 100);
});

Without timeout/visible animation

document.addEventListener('turbolinks:load', () => {
    M.updateTextFields();
});

Rails 5 with Turbolinks, and Materialize CSS 1.0.0

Steve Meisner
  • 666
  • 9
  • 17
1

Add class="active"into the label tag associated with the input field.

Darryl Mendonez
  • 1,081
  • 1
  • 15
  • 27
0

With JQuery you can use $('#yourInputText').change();

ferchoman09
  • 62
  • 1
  • 12
0

If you are using older version (0.x) of Materializecss, use:

Materialize.updateTextFields(); 

instead of:

M.updateTextFields();
Obsidian
  • 3,719
  • 8
  • 17
  • 30
0

For anyone looking for solution in ReactJS:

  1. link the value property of the input to some value in your Component's state. (Eg: value={this.state.name})
  2. Add the line document.M.updateTextFields() to the componentDidMount() lifeCycle method of your Component.

The above solution helps when there are certain values which need to be prefilled into a Form. (Eg: Update Details Form)

thewebjackal
  • 785
  • 8
  • 17