How to avoid the Chips component of the Materialize in white?

1

I'm using the materialize chips in my project but wanted to avoid this default behavior of adding the same empty tag, for example:

How do I prevent this and insert the tag only when I have at least one character?

What I got closer was:

$('.chips').on('chip.add', function(e, chip){
        console.log(chip);

        var chip = chip.tag;

        if(!chip.trim()){
           alert('CHIP VAZIO!');
           //aqui gostaria de fazer algo do tipo chip.remove() porém da erro
        }
    });
    
asked by anonymous 11.12.2018 / 18:12

1 answer

2

Verify that the chip's text node is empty using the .trim() method. If only spaces are entered, trim () will delete them and render the chip null.

For this you use the callback method onChipAdd :

$('.chips').chips({
    onChipAdd: function(e, c){
      if(!c.firstChild.textContent.trim()) c.remove();
    }
});

The second parameter ( c ) returns the HTML of the created chip. The first node ( firstChild ) is the text. If it is empty remove it with .remove() .

Test:

$('.chips').chips({
    onChipAdd: function(e, c){
      if(!c.firstChild.textContent.trim()) c.remove();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><linkrel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script><divclass="chips">
   <input class="custom-class" placeholder="Digite as tags">
</div>
    
11.12.2018 / 20:38