Materialize Javascript autocomplete

Asked

Viewed 387 times

1

I’m using the materialize framework. According to the documentation, I can use "autocomplete" in the form tag according to the link Materialize Form. My doubt, is the following I want to create a javascript for extensions autocomplete, example: @gmail.com, @outlook.com, @Hotmail.com. When the user enters "@" this list appears. Below my code

  <div class="row">
            <div class="input-field col l6">
                <i class="material-icons prefix">email</i> 
                <input type="email" id="email" class="validate" autocomplete="off">
                <label data-error="E-mail invalido!" data-success="E-mail valido!" for="nome">E-mail</label>           
            </div>           
        </div>

Javascript:

     <script>
        //Função para autocomplete do email
        $(document).ready(function(){
            //pegando o id do formulario
            $('#email').autocomplete({
//Aqui declaro algumas possiveis extensoes de email para autocompletar
                data: {
                    "@hotmail.com": null, /
                    "@gmail.com": null,
                    "@outlook.com": "img/outlook.jpg",
                },
                limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
                onAutocomplete: function(val) {
                    // Função quando é valido ou seja completado!
                    //alert("ok"); 
                },
                minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.
            });
        });        
    </script>
  • And what’s going wrong in your code?

1 answer

1


From what I’ve researched, autocomplete does not yet have a feature to display suggestions only after certain user input. I saw that it is in the plugin’s upgrade list.

"When the user enters "@" this list appears."

If I understand what you need, follow an alternative...

Note: The default working of the plugin has been modified.

//Função para autocomplete do email
$(document).ready(function() {
  //pegando o id do formulario
  $('#emailAux').autocomplete({
    //Aqui declaro algumas possiveis extensoes de email para autocompletar
    data: {
      '@hotmail.com': null,
      '@gmail.com': null,
      '@outlook.com': null
    },
    limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
    onAutocomplete: function(val) {
      // Função quando é valido ou seja completado!
      //alert("ok");
    },
    minLength: 1 // The minimum length of the input for the autocomplete to start. Default: 1.
  });

  detectChanges();
});

let lastLength = $('#emailAux').val().length;

$('#email').on('input', function(e) {
  let countSymbol = $(this)
    .val()
    .match(/@/g);
  if (countSymbol) {
    if (countSymbol.length == 1) {
      if ($('.autocomplete-content').is(':visible')) {
        $('#emailAux').val($('#email').val().substr($('#email').val().indexOf('@')));
        $('#emailAux').trigger(
          jQuery.Event('keyup', {
            keycode: 13
          })
        );
      } else {
        $('#emailAux').val('@');
        $('#emailAux').text('@');
        $('#emailAux').trigger(
          jQuery.Event('keyup', {
            keycode: 13
          })
        );
        $('.autocomplete-content').show();
        e.stopPropagation();
      }
      lastLength = $('#emailAux').val().length;

    } else {
      $('.autocomplete-content').hide();
    }
  } else {
    $('.autocomplete-content').hide();
  }
});

$('#email').on('blur', function(e) {
  $('#emailAux').blur();
});

let intervalID = null;

intervalManager(true, detectChanges, 1);

function intervalManager(flag, animate, time) {
  if (flag) intervalID = setInterval(animate, time);
  else clearInterval(intervalID);
}

function detectChanges() {
  if ($('#emailAux').val().length - lastLength > 1) {
    $('#email').val($('#email').val().substr(0, $('#email').val().indexOf('@')) + $('#emailAux').val());
    $('#email').focus().blur();
    intervalManager(false);
    $('#emailAux').val('');
    intervalManager(true, detectChanges, 1);
  }
}
.autocomplete-content {
  display: none;
}

.aux {
  display: none;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>

<div class="row">
  <div class="input-field col l6">
    <input type="email" id="email" class="validate" autocomplete="off">
    <input id="emailAux" class="aux" autocomplete="off">
    <label data-error="E-mail invalido!" data-success="E-mail valido!" for="nome">E-mail</label>
  </div>
</div>

  • Got it! But a question, as I start the account after @, example: bruno@o (logically it would appear in the list @outlook.com). Thanks for the idea!

  • Eai @Brunolima, I edited the answer, man, I ran the code, da para melhorar mt thing but the idea is this... I created an invisible input that has the autocomplete plugin, everything that is typed in the visible input is replicated in the invisible... The rest are events to handle, for example, the click on an autocomplete item, any doubt calls ae =)

  • Thank you so much for sharing your idea! I confess that I am not very good with javascript (I am student yet), It was perfect! Hugs!

Browser other questions tagged

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