Change chips default behavior materialize

Asked

Viewed 112 times

1

You can add a tag with the user clicking enter E on space? By default of materialize chips it adds only if you click enter...

I found nothing on, the documentation of the materialize is very bad.

For example, if you are separated by spaces and click on enter it looks like this: inserir a descrição da imagem aqui

The right thing would be:

inserir a descrição da imagem aqui

$('.chips').chips();
body {
  padding: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<div class="chips"></div>

  • @Andersoncarloswoss put images demonstrating.

1 answer

2

To add chips with the space key, just add the one function to the method onkeyup. This way you can detect which keys the user pressed; if it is the space, just use the function addChip.

Example:

/* Instancia e cria os campos */
let chips = $('.chips').chips();

/**
 * 1. Captura as instancias do Chip
 * 2. Procura o campo utilizado para escrita
 * 3. Adiciona o evento "keyup" para detecção das teclas
 */
$(chips).find("input").on("keyup", function(e) {

  /* Verifica se o usuário pressionou a tecla "espaço" */
  if (e.keyCode == 32) {
  
    /**
     * Captura a instância do "chip"
     * Isto permitirá adicionar, deletar ou selecionar as opções
     */
    let instance = M.Chips.getInstance($(this).parent());
    
    /* Adiciona o "chip" no campo */
    instance.addChip({
      tag: this.value
    })
    
    /* Limpa o campo de texto */
    this.value = ""
  }
})
body {
  padding: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<div class="chips"></div>

  • I am using version 0.100.2 of materialize, because this way gave this error in the console "M is not defined" will be because of the version?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.