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?
问题:
回答1:
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.
回答2:
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.
回答3:
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
回答4:
Add class="active"
into the label
tag associated with the input field.
回答5:
With JQuery you can use $('#yourInputText').change();