0

I am making an autocomplete search bar using codeigniter, i am getting data through ajax call, the data is coming in an array as i checked it using the command print_r(). The data is coming in array.

Now in ajax data is also coming in console.log, here is my code of ajax:

$(document).ready(function(){
    $('#country_id').keyup( function() {
        var min_length = 0; 
    var keyword = $('#country_id').val();
    if (keyword.length >= min_length) {
        $.ajax({
            url: 'http://localhost/new/index.php/travels/search_fields',
            type: 'POST',
            data: { term: $("#country_id").val()},
            success:function(data){
                console.log(data);
            }
        });
    }
});
});

Now I want to show that data in a drop down below the input field. What should i do now? Please help me out.

Harris Khan
  • 247
  • 10
  • 26
  • Possible duplicate of [Adding options to select with javascript](http://stackoverflow.com/questions/8674618/adding-options-to-select-with-javascript) – Madhawa Priyashantha Nov 19 '16 at 12:20

2 Answers2

0

Try following,

 $(document).ready(function(){
$('#country_id').keyup( function() {
    var min_length = 0; 
    var selectEl = $("<select id=\"selectId\" name=\"selectName\" />");
    var keyword = $('#country_id').val();
        if (keyword.length >= min_length) {
            $.ajax({
                url: 'http://localhost/new/index.php/travels/search_fields',
                type: 'POST',
                data: { term: $("#country_id").val()},
                success:function(data){

                   // Do this if returned data is not valid javascript array : var jArray = jQuery.makeArray(data);
                   var option = '';
                  $.each(data, function (i, item) {
                selectEl.appen($( '<option value="'+ item + '">' + item + '</option>') );
                  });

                 }
            });
        }
      //finally add select list below the input
      $(this).after(selectEl);
    });
});
ScanQR
  • 3,740
  • 1
  • 13
  • 30
0

Try this

var select_data = '';
$.each(data, function (i, item) {
    select_data += "<option value=''>'+item.some_value+'</option>";                
});
$(".your_append_identifier").append(select_data);
Amir Hossain
  • 673
  • 13
  • 26