Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to activate focus on material design web component text field?

Tags:

I have this code

    this.mdc_text = mdc.textField.MDCTextField.attachTo(this.$el);
    if (this.autofocus) {
        this.mdc_text.activateFocus();
    }

but the function activateFocus is undefined. How can I focus it?

https://material.io/develop/web/components/input-controls/text-field/

Thanks

like image 431
omega Avatar asked Oct 29 '18 20:10

omega


1 Answers

activateFocus is used with MDCTextFieldFoundation when creating a component for a framework. In your case, it looks like you are trying to programmatically focus an MDC textfield, so use the focus method instead.

const field = mdc.textField.MDCTextField.attachTo(document.querySelector('.mdc-text-field'));
field.focus();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Material TextField</title>
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
    <script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>   
  </head>
  <body>  
    <label class="mdc-text-field mdc-text-field--filled">
      <span class="mdc-text-field__ripple"></span>
      <input class="mdc-text-field__input" type="text">
      <span class="mdc-floating-label">Hint text</span>
      <span class="mdc-line-ripple"></span>
    </label> 
  </body>
</html>

As an aside, if you want a the TextField to be automatically focused on page load, then you can add the autofocus attribute to the input element in your html.

like image 121
benvc Avatar answered Nov 09 '22 08:11

benvc