Shinoy p b
Shinoy p b

Reputation: 393

Dynamically loading multiple select box using JavaScript

In my CodeIgniter view page , I want to display a searchable select box .And I can manipulate any number of copies of searchable select box using a add button . The searchable select box data filled by ajax call .This is my requirement ,I am adding a picture below to clarify my problem.

My requirement picture

I am providing my CodeIgniter controller function below that handles ajax request:

public function ajax_load()
{

    if ($this->input->is_ajax_request())
    {

        $labtests = $this->Laboratory_service_model->getLabTests(); //gets result_array()

        if (!empty($labtests))
        {

            $data['return'] = true;
            $data['a'] = $labtests;
            
            echo json_encode($data);
        }
        else
        {
            $data['return'] = false;
            $data['message'] = 'cant get data from table';
            echo json_encode($data);
        }
    }
    else
    {
        $data['return'] = false;
        $data['message'] = 'Ajax request not getting';
        echo json_encode($data);
    }



}

And my JavaScript file provide here :

$.ajax({
        type: 'POST',
        url: surl + 'LabServices/ajax_load',

        success: function (data)
        {
            var ndata = JSON.parse(data);


            if (ndata.return == true)
            {
                var myOptions = ndata.a;

                var mySelect = $('#mySelect');

                myOptions.forEach(function(data)
                {
                    mySelect.append(
                        $('<option></option>').val(data.id).html(data.name)
                    );
                });

            }
            else if (ndata.return == false)
            {
                $('.error').text(ndata.message);
            }
            else
            {
                $('.error').text('something went wrong');
            }

        },
        error: function ()
        {
            $('.error').text('something went wrong');
        }

    });

I already fetched data from controller using ajax and created a searchable select box ,with the help of select2 library in CodeIgniter. But I dont know how to dynamically manipulate select box with buttons .Please give me a solution friends..

And my view page section is :

                <a class="col-md-6 mb-3 htmlitems">
                    <label>Lab Tests</label>
                    <div class="form-control ">
                        <select id="mySelect" class="" style="width: 100%;" name="tests">

                        </select>
                    </div>
                    <a id="" class="btn btn-danger add_spec"> + </a>
                </div>

Thanks in advance Shinoy

Upvotes: 2

Views: 1251

Answers (1)

Swati
Swati

Reputation: 28522

As your select option will be same so onclick of add_spec instead of calling ajax to retrieve options again you can just clone options of already added select and then add this cloned to your htmls . Then, intialize it using find('select:last').select2();.

Demo Code :

$("#mySelect").select2();
$(".add_spec").click(function() {
  var options = $(".htmlitems:first").find("[name=tests]").clone(); //get select and clone it
  //generate html and add options inside select
  var result = '<div class="col-md-6 mb-3 htmlitems"><label>Lab Tests</label><div class="form-control "><select class="new_added" style="width: 100%;" name="tests">' + $(options).html() + '</select><button class="remove">-</button></div>'
  $(result).appendTo("#result") //add generated htmls 
  $('#result').find('select:last').select2(); //initialize it

});
//on click of remove
$(document).on("click", ".remove", function() {
  $(this).closest(".htmlitems").remove() //get closest div remove it
})
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div id="result">
  <div class="col-md-6 mb-3 htmlitems">
    <label>Lab Tests</label>
    <div class="form-control ">
      <select id="mySelect" class="" style="width: 100%;" name="tests">
        <option>1</option>
        <option>2</option>
        <option>3</option>
      </select>
    </div>
    <a id="" class="btn btn-danger add_spec"> + </a>
  </div>
</div>

Upvotes: 1

Related Questions