jQuery addClass example

Change class name on click in jQuery

by Dedi Wibisono

HTML

<main>

    <div class="container">
        <div id="main_panel_form" class="card-panel col s12">
            <div class="row">
                <form class="col s12" action="/test">
                    <div class="row">
                        <div class="input-field col s4">
                            <input id="name_autocomplete" name="name_autocomplete" type="text" class="autocomplete">
                            <label id='label_name_autocomplete' for="name_autocomplete" class="active">Name</label>
                        </div>
                        <div class="input-field col s3">
                            <input id="id" name="id" type="text" class="autocomplete">
                            <label id="label_id" for="id">ID</label>
                        </div>
                    </div>

                    <div class="row center-align">
                        <button class="btn waves-effect waves-light" type="submit" value="Submit">Submit</button>
                    </div>

                </form>
            </div>

        </div>
    </div>
</main>

CSS

body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}

JavaScript

$(document).ready(function () {
  //Autocomplete
 autoComplete('https://reqres.in/api/users?page=1')
  
 $('#name_autocomplete').keyup(function () {
    autoComplete('https://reqres.in/api/users?page=2', true)
  });
  
  function autoComplete(url, update) {
    $.ajax({
      type: 'GET',
      url: url,
      success: function(response) {
        autoCompleteSuccess(response, update);
      }
    });
  }
  
  function autoCompleteSuccess(response, update) {
    var nameArray = response.data;
    var dataName = {};
        for (var i = 0; i < nameArray.length; i++) {
      dataName[nameArray[i].last_name] = nameArray[i].flag;
    }
    
    if(update) {
      const pozycje_autocomplete = document.querySelector('#name_autocomplete');
    let instance = M.Autocomplete.getInstance(pozycje_autocomplete);

      instance.updateData(dataName)
    } else {
       $('#name_autocomplete').autocomplete({
      data: dataName,
      limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
    });
    }
  }
});