jQuery addClass example

Change class name on click in jQuery

by Dmitri Ganenco

HTML

<table class="table table-hover small-text" id="tb">
  <tr class="tr-header">
    <th>Vehicle Number</th>
    <th>Rate</th>
    <th>Driver Name<a data-toggle="modal" data-target="#contact-modal-2">
        <span class="glyphicon glyphicon-plus-sign"></span>
      </a> </th>
    <th><a href="javascript:void(0);" style="font-size:18px;" id="addMore" title="Add More Person"><span class="glyphicon glyphicon-plus"></span></a></th>
  <tr>
    <td>
      <select name="vehicle_id[]" class="form-control">
        <option value="" selected>Select Vehicle</option>
        @foreach($car_no as $car_no)
        <option value="{{$car_no->id}}">{{$car_no->car_number}}</option>
        @endforeach
      </select>
    </td>

    <!-- <td><input type="text" name="rate[]" value="" class="form-control rate" ></td> -->
    <td>
      <div class="inputContainer">
    </td>
    <td>
      <select name="driver_id[]" class="form-control">
        <option value="" selected>Select Driver</option>
        @foreach($driver_detail as $driver_detail)
        <option value="{{$driver_detail->id}}">{{$driver_detail->name}}</option>
        @endforeach
      </select>
    </td>

    <td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
  </tr>
</table>

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

$("select[name='vehicle_id[]']").change(function() {
   var vehicle = $(this).val();
   console.log(vehicle);
   var token = $("input[name='_token']").val();
   $.ajax({
     url: "<?php echo url('admin/rate') ?>",
     method: 'POST',
     data: {
       vehicle: vehicle,
       _token: token
     },
     success: function(data) {
       console.log(data);
       $(".inputContainer").each(function() {
         $(this).find('option').not(':first').remove();
       });
       $.each(data, function(i, item) {

         const $input = $('<input />')
           .addClass('form-control rate')
           .attr('name', 'rate[]')
           .attr('id', 'rate' + i)
           .attr('type', 'text')
           .attr('readonly', 'readonly')
           .val(item.rate)

         // here we append it into container
         $('.inputContainer').append($input);
       });
     }
   });
 });