Add Chip from materialize if user forgets to click enter

1

I have a registration screen that has a tags field. As it fills in and press enter, it looks like this:

Let'ssayhesignedupbutforgottoenterenterintoatag,forexample:

This tag will be lost, when it clicks edit this register will only have A, B and C.

How could I do this? When it clicks register, see if all the elements are inside: $('.chips').material_chip('data')); if one does not have, insert.

    
asked by anonymous 12.12.2018 / 14:01

1 answer

3

You can do this:

// evento submit do formulário
$("form").on("submit", function(){

   // pega o valor do que foi digitado e não foi incluído no chip
   var chipp = $(".chips input").val().trim();

   // se não for null
   if(chipp){
      // adiciona o chip ao array
      var obj = {};
      obj["tag"] = chipp;
      $('.chips').material_chip('data').push(obj);

      // renderiza todos os chips
      // se você só precisa da array, talvez o código abaixo não seja necessário
      $('.chips').material_chip({
         data: $('.chips').material_chip('data')
      });


   }
});

Example without submitting the form for viewing:

$("form").on("submit", function(e){
   
   e.preventDefault();
   var chipp = $(".chips input").val().trim();
   
   if(chipp){
      var obj = {};
      obj["tag"] = chipp;
      $('.chips').material_chip('data').push(obj);

      $('.chips').material_chip({
         data: $('.chips').material_chip('data')
      });

      console.log($('.chips').material_chip('data'));

   }
});


$('.chips').material_chip('data');
$('.chips').material_chip();
<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/0.100.2/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script><formmethod="post" action="teste2.php">
<div class="chips">
   <input name="tags" class="custom-class" placeholder="Digite as tags">
</div>
<button>OK</button>
</form>
    
12.12.2018 / 14:41