Search code examples
javascripthtmlmaterialize

How to disable user input for materialize autocomplete


Essentially, I want to force the user to be able to only select from the given values.

E.g when the user either selects or clicks inside the text box then it should display him/her some of the values (e.g Microsoft and google) and then he should be able to select either one of them or type a and then select apple but under no circumstances, he should be able to input or select anything that's not in the data/values.

CodePen: https://codepen.io/textech/pen/WNvrLMp

  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.autocomplete');
    var instances = M.Autocomplete.init(elems, {
      data: {
        "Apple": null,
        "Microsoft": null,
        "Google": 'https://placehold.it/250x250'
      },

    });
  });

Solution

  • Passing 'minLength: 0' into the initialisation brings up the options as soon as you click into the text field:

    document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.autocomplete');
        var instances = M.Autocomplete.init(elems, {
          data: {
            "Apple": null,
            "Microsoft": null,
            "Google": 'https://placehold.it/250x250'
          },
          minLength: 0,
    
        });
      });
    

    Forked codepen:

    https://codepen.io/doughballs/pen/XWbXQZY

    Documentation:

    https://materializecss.com/autocomplete.html#options

    EDIT

    I've added a listener to the autocomplete (jQuery but you can rework if necessary) - it hooks into the instance to check 'count', which is how many options are currently being returned. If this is 0 - ie no match - we clear the autocomplete.

    I'll update the codepen :D

    $('#autocomplete-input').on('keyup',function(){
      console.log('keyup')
       if ( instances[0].count === 0 ) {
         console.log('no matches');
         $('#autocomplete-input').val('');
       }
    })