Search code examples
cssasp.netfrontendmaterializeweb-frontend

Navbar with search box - MaterializeCss


I'm trying to create a functional search bar inside my nav bar with materializecss. I can put the search icon and write text inside it but it doesn't work. I only have the design part. I'm not being able to find the jquery to initialize the search box and make it work.

<ul class="right hide-on-med-and-down">
                        <li>
                            <div class="input-field col s6 s12 white-text">
                                <i class="white-text small material-icons prefix">search</i>
                                <input type="text" placeholder="search" id="autocomplete-input" class="white-text">
                            </div>
                        </li>
</ul>

Solution

  • You have not initialized autocomplete and it's options in JS file. You can check JS code below.

    Try to run the demo below, a search bar with implemented autocomplete. You can get Apple, Microsoft and Google in the search bar autocomplete. For more options add them in the data object under autocomplete initialization.

    var myData={
          "Apple": null,
          "Microsoft": null,
          "Google": 'https://placehold.it/250x250'
        };
    
    $(document).ready(function() {
      $('input.autocomplete').autocomplete({
        data: myData,
        limit: 20, // The max amount of results that can be shown at once. Default: Infinity.
        onAutocomplete: function(val) {
          // Callback function when value is autcompleted.
        },
        minLength: 1, // The minimum length of the input for the autocomplete to start. Default: 1.
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
    
    
    
    <div class="row">
      <div class="col s12">
        <div class="row">
          <div class="input-field col s12">
            <i class="material-icons prefix">search</i>
            <input type="text" id="autocomplete-input" class="autocomplete">
            <label for="autocomplete-input">Search</label>
          </div>
        </div>
      </div>
    </div>