How can I edit dropdown or Select option list using Ajax when I click on edit button?

  ajax, laravel, php

I am using Laravel-8. I want to edit my dropdown list. When I click on the Edit button I can not set the specific value into the dropdown / select option field using Ajax. Please help me.

My Dropdown Code:

<div class="ibox-content">
   <input type="hidden" id="area_id">
   <div class="form-group row">
      <label class="col-lg-3 col-form-label">Select City</label>
      <div class="col-lg-9">

      <select class="form-control" id="selectCity">
          <option value="0" selected disabled>--- Select City ---</option>
          @foreach ($cities as $city)
          <option value="{{ $city->id }}">{{ $city->city_name }}</option>
          @endforeach
       </select>
     </div> 
    </div>
    <div class="form-group row">
    <label class="col-lg-3 col-form-label">Add Area</label>
       <div class="col-lg-9">
          <input type="text" id="areaName" placeholder="Enter Area Name" class="form-control">
        </div>
       </div>

<div>
   <button class="btn btn-sm btn-primary btn-outline float-right m-t-n-xs" id="updateArea" type="submit">Update Area</button>
   <label> </label>
   </div>
 </div>

I have an Edit button which code is below. This works fine.

success: function(response) {
$(‘#areaTable tbody’).html(”);

$.each(response.areas, function(key, item) {
   i++;
   $('#areaTable tbody').append(
    '<tr class="grade"><td>' + i + '</td><td>' + item.city_name + '</td><td>' + item.area_name +'</td><td><button class="btn btn-sm btn-primary btn-outline" type="submit" value="' +item.id +'" id="edit_area"><i class="fa fa-edit"></i></button>&nbsp;&nbsp;<button data-toggle="modal" data-target="#cityModal" class="btn btn-sm btn-danger btn-outline" id="btn-delete-area" type="submit" value="' +item.id + '"><i class="fa fa-trash"></i></button></td></tr>');
      });
   }

Here is my Ajax code:

// Edit Area from Database
            $(document).on('click', '#edit_area', function(e) {
                e.preventDefault();
                var area_id = $(this).val();
                // console.log(area_id);
                $.ajax({
                    type: "GET",
                    url: "/edit-area/" + area_id,
                    success: function(response) {
                        if (response.status == 400) {
                            //some staff goes here
                        } else {
                            $('#area_id').val(area_id);
                            $('#areaName').val(response.area[0].area_name);
                            $('#selectCity').val(response.area[0].city_name); //this is not works for me
                        }
                    }
                });
            });

Source: Laravel

Leave a Reply