Search code examples
javascriptgoogle-apps-scriptmaterialize

MaterializeCSS onAutocomplete not triggering javascript callback function


I am using Materialize CSS to create a Google Web App linked to our company's Google Drive for some basic document flow processes. I am trying to create an autocomplete text field that when a user begins typing the name it populates options and when an option is selected it triggers the onAutocomplete callback and autofills some following fields based off of the client selected. Getting the field to autocomplete is no problem, but I can't get the onAutocomplete callback to trigger.

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" 
    href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
    <?!= include("pageCSS"); ?>
  </head>
  <body>
    <div class="row input-field">
        <input  class="autocomplete"type="text" id="autocompleteField"/>
        <label for="infoModalName">Client Name</label>
    </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"> 
  </script>
  <?!= include("pageScripts"); ?>
  </body>
</html>
<script>
function populateWords(words){
        
    //console.log(words)

    var autoComplete = document.getElementById("autocompleteField");
    M.Autocomplete.init(autoComplete, {data: words}, {onAutocomplete: function() 
       {console.log("Hello")}});

}
</script>

Right now, I am just trying to get the callback function to output anything, not write to the other fields. A lot of the documentation online uses the JQuery setup, but this is the last thing I need to get working and I have not used any JQuery to this point, so I would rather stick with a Javascript solution if possible.


Solution

  • It seems that the arguments of M.Autocomplete.init is like M.Autocomplete.init(elems, options). Ref And also, it seems that the value of words is required to be an object. When these are reflected in your script, it becomes as follows.

    Modified script:

    In this modification, please modify populateWords as follows.

    function populateWords(words){
      words = {key: "value"};  // This is a sample value for testing this modification.
      var autoComplete = document.getElementById("autocompleteField");
      M.Autocomplete.init(autoComplete, {data: words, onAutocomplete: function() {console.log("Hello")}});
    }
    
    • In this modification, when k is put to the text input, the autoComplete is run and when key is selected, console.log("Hello") is run.

    Note:

    • Unfortunately, from your question, I couldn't know the value of words in your script. So I used a sample value. Please modify it for your actual situation.

    Reference: