Change behavior default chips materialize

1

Can you add a tag to the user by clicking the enter E in the space ? By default the materialize chips it adds only if you click enter ...

I did not find anything about it, the materialize documentation is pretty bad.

For example, if you are separating by spaces and clicking the enter it looks like this:

The right thing would be:

$('.chips').chips();
body {
  padding: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkrel="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><divclass="chips"></div>
    
asked by anonymous 21.12.2018 / 19:53

1 answer

2

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

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><linkrel="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><divclass="chips"></div>
    
21.12.2018 / 22:56