2

Currently I'm using a controller to fetch all my data and placing it in a foreach statement in my view class. So whenever the page is loaded, it executes this function. To achieve this I used something like this:

Controller Class:

$add['sources']= $this->contacts_model->get_array();

View class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
          <option value="">Select</option>
          <?php foreach($sources as $source): ?>
          <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
          <?php endforeach; ?>
   </select>

But now I want the page to load faster, so for that I want to load the dropdown only when the user has clicked on that particular select2 statement. I've tried the following code to get the select2 variables with the select 2 functionality of getting an input text with dropdown, but none of them work. It just brings up a normal dropdown that loads when my page loads.

View Class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
              <option value="">Select</option>
              <?php foreach($sources as $source): ?>
              <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
              <?php endforeach; ?>
</select>

$(document).ready(function(){
  $('#contact_source').on('click', function(e) {
    $("#contact_source").select2({
      minimumInputLength: 2,
      tags: [],
      ajax: {
          url: "<?php echo site_url('contacts/add'); ?>/",
          dataType: 'json',
          type: "GET",
          delay : 50,
          data: function (data) {
              return {
                sources: data.sources
              };
          },
          results: function (data) {
              return {
                  results: $.map(data, function (item) {
                      return {
                          text: item.sources,
                          id: item.id
                      }
                  })
              };
          }
      }
  });
})
});
H2O
  • 313
  • 2
  • 9
  • Did you ever see this one. https://stackoverflow.com/questions/20926707/how-to-use-select2-with-json-via-ajax-request – Raphael Nov 10 '21 at 06:15

1 Answers1

1

Remove select2 in <select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>

and remove also $('#contact_source').on('click', function(e) {

And I recommend jQuery Autocomplete. https://jqueryui.com/autocomplete/#remote

Raphael
  • 517
  • 4
  • 18