Showing designation_id based on department_id and also showing the current designation as selected using ajax

Viewed 26

In my employees edit page I'm showing the employees department and designation. Then when editing the employee, all of the designations are shown on the drop down list regardless of the selected department.

So I tried showing the designations based on the departments and I did show the designations based on selected department. But then I no longer can keep the specific employees designation selected. I tried doing this in Laravel application.

Here are my codes:

Page(edit.blade.php):

@section('scripts')

{{-- To show Designations based on Departments --}}
<script type="text/javascript">
    $(document).ready(function() {
        $('select[name="department_id"]').on('change', function(){
        // $('#department_id').on('change', function(){
            var department_id = $(this).val();
            console.log(department_id);
            if(department_id) {
                $.ajax({
                    url: "{{  url('admin/employee/designation') }}/"+department_id,
                    type:"GET",
                    dataType:"json",
                    success:function(data) {
                        console.log(data);
                    var d =$('select[name="designation_id"]').empty();
                        $.each(data, function(key, value){
                            $('select[name="designation_id"]').append('<option value="'+ value.id +'">' + value.designation_name + '</option>');
                        });
                    },
                });
            } else {
            alert('danger');
            }
        });
    });
</script>

@endsection 

In my Controller:

public function GetDesignation($department_id){

    $designations = Designation::where('department_id', $department_id)->orderby('designation_name', 'ASC')->get();

    return json_encode($designations);
}
// End Method
1 Answers

This happens because you are completely emptying the select upon each fetch request which causes it to lose its selected value.

If you want to do it this way, you need to set the select value back to what it was before you emptied it.

Something like this:

$.ajax({
    url: "{{ url('admin/employee/designation') }}/" + department_id,
    type: "GET",
    dataType: "json",
    success: function (data) {
        let d_id_select = $('select[name="designation_id"]');
        let d_id_val = designation_id_element.val();

        d_id_select.empty();

        $.when(
            $.each(data, function (k, v) {
                d_id_select.append('<option value="' + v.id + '">' + v.designation_name + '</option>');
            })
        ).then(function () {
            d_id_select.val(d_id_val);
        });
    },
});

Related