chris.cavage
chris.cavage

Reputation: 881

Set initial value of select2 from ajax string

I'm using select2 v. 4.0.3

I have two fields on my form that once shown, an ajax call is made to populate the form data.

When the ajax call is made and on success, I want to populate the select2 boxes based on the values from "left_options" and "right_options" which are the two fields in my database that hold integer strings like this: 25,0 or 3,41,4

 //get all the record info and fillfields if in update mode
 $.ajax({
 url: "ajax_quick_get_value.php",
 type: "get",
 data: {
     table: 'invoice_hearing_aids',
     field: 'id',
     field_equals: $('#modal_form_invoice_hearingaids #hearing_aids_id').val()
 },
 dataType: 'json',
 success: function (response) {
//response here if data response

if (response) {

 //loop through the data and fill form fields based on id's
    $.each(response, function (index, value) {
        if(index != 'left_options' || index != 'right_options') {
            $('#modal_form_invoice_hearingaids #hearing_aids_' + index).val(value);
        }

        if(index == 'left_options') {
            var left_current_string = value;

            //will throw an error if it's null, so check first
            if (left_current_string != null) {
                var left_array = new Array();
                var left_array = left_current_string.split(',');

                $('#modal_form_invoice_hearingaids #hearing_aids_left_options').select2('val', left_array);
            }

        }

        if(index == 'right_options') {
            var right_current_string = value;

            //will throw an error if it's null, so check first
            if (right_current_string != null) {
                var right_array = new Array();
                var right_array = right_current_string.split(',');

                $('#modal_form_invoice_hearingaids #hearing_aids_right_options').select2('val', right_array);
            }
        }

    });

I'm able to confirm that the JSON data being returned from my ajax call has values for both left_options and right_options that are separated by a comma.

Only the first value from the options string is being populated into the select2 boxes. Everything else after that is not populated.

 $('#modal_form_invoice_hearingaids #hearing_aids_left_options').select2('val', left_array)

I think the problem is in the above code somehow? Same thing for the right_options code.

I feel like this worked, but suddenly stopped for some reason. I use Chrome.

Here is how I populate my select2 with the options dynamically (just showing the right_options one here):

 <div class="form-group">
                <label class="control-label"></label>
                <select id="hearing_aids_right_options"  name="right_options[]" class="form-control hearing_aid_options" multiple style="width: 100%">
                <?php 
if($company->find_hearing_aid_options()) { 
$options = $company->hearing_aid_options(); 
foreach ($options as $option) { 
    echo '<option value="' .  $option->id . '">' .  $option->name . '</option>';
     };
};
 ?>
 </select>

I'm not sure if I need to supply more code, but I can. Thanks.

Upvotes: 2

Views: 1062

Answers (2)

chris.cavage
chris.cavage

Reputation: 881

This worked for me by changing the code to:

 $('#modal_form_invoice_hearingaids #hearing_aids_left_options').val(left_array).trigger("change");

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50787

You need to construct the data in the correct way on the server side so it returns an array of key:value pairs inside of an array named items[]. Furthermore, select2 has it's own thoughts regarding handling data in the success of an ajax request, and therefore you should utilize the libraries implementation, for example:

$('select').select2({
     ajax: {
        url: "ajax_quick_get_value.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
          return {
            q: params.term, // search term
            page: params.page
          };
        },
        processResults: function (data, params) {
          params.page = params.page || 1;

          return {
            results: data.items,
            pagination: {
              more: (params.page * 30) < data.total_count
            }
          };
        },
        cache: true
      },
      escapeMarkup: function (markup) { return markup; },
      minimumInputLength: 1,
      templateResult: formatItems, 
      templateSelection: formatItemSelection
    });
});

Now the only thing you'll need to worry about is the 2 functions formatItems and formatItemSelection.

You can just implement something simple for these, like:

function formatItems(item) {
    return item.name;
}

and

function formatItemSelection (item) {
    return item.name;
}

That's it. Now you just need to make sure, on the server side, it's returned correctly in such a way that it's a proper JSON response as described above:

return json_encode([
    'items' => $myItemsArray
]);

Then you just need to return an array of objects that have an id property and a name property at the minimum.

Upvotes: 0

Related Questions