Skip to content
Advertisement

Select2 is not selected when update a select field by ajax call

I am facing a problem when I use select2 class in select option. When I insert a form data using a field select2 class by ajax call then it is working properly

But when I update that select2 field by ajax calling same form firstly it is not selected value that I inserted first.

Note

ajax response is working properly

cdn, css and javascript integrated properly

I have tried below

Input Field

<div class="form-group">
    <label for="inputEmail3" class="col-sm-5 control-label">Status:</label>
    <div class="col-sm-7">
        <select class="form-control select2" name="status_user" id="status_user" style="width:100%;">
            <option value="">-Select-</option>
            <option value="1">Active</option>
            <option value="0">Inactive</option>
         </select>
    </div>
</div>

Javascript

$(document).ready( function () {

    $('.select2').select2()

} );

Ajax Update

$('#status_user').val('');

$.ajax({

        type:"post",

        url:"./cc/xyz.php",

        data: {
            row_id:                 action_id,
            conditional_value:      14
        },

        success:function(response){

            var responseData =  JSON.parse(response);
            $('#status_user').val(responseData.status_user);
            
        }
    });

Advertisement

Answer

I was facing same problem few days ago. I have solved this issue from Select2 Documentation

$('#status_user').val('');

Replace by this

var statusSelect = $('#status_user');

And in your ajax request add new line

$('#status_user').val(responseData.status_user);
statusSelect.append(responseData.status_user).trigger('change'); // Add this line
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement