jQuery addClass example

Change class name on click in jQuery

by pedrom69

HTML

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>

   <div class="container">
      <button type="button" class="btn btn-primary">Click Me</button>
      <br>
      <select class="form-control selectpicker" id="testpicker" data-lastselected="Ketchup">
         <option>Mustard</option>
         <option selected="">Ketchup</option>
         <option>Relish</option>
      </select>
   </div>

JavaScript

$('button').on('click', function() {
         $('#testpicker').selectpicker('val', 'Mustard');
      })

      $('select').on("change", function() {
         if (!confirm("Sure you want to change to " + $('#testpicker').val())) {
            $('#testpicker').selectpicker('val', $('#testpicker').data('lastselected'));
         } else {
            $('#testpicker').data('lastselected', $('#testpicker').selectpicker('val'));
            alert('Changed');
         }
      })