Get the value of selected option in select2 and then set the value to an input text using jquery?

You are almost there. Put your value assignments within the change handler of the dropdown. The way you have it, it's just getting called when the page is loaded.

  $(function(){
    // turn the element to select2 select style
    $('.select2').select2({
      placeholder: "Select a state"
    });

    $('.select2').on('change', function() {
      var data = $(".select2 option:selected").text();
      $("#test").val(data);
    })
  });

As per the docs https://select2.org/programmatic-control/events#event-data

$('.select2').on('select2:select', function (e) {
    var data = e.params.data;
    $('#test').val(data.text);
});

You can use change event: whenever an option is selected the value can be copied to the text box:

$(function(){
  // turn the element to select2 select style
  $('.select2').select2({
    placeholder: "Select a state"
  }).on('change', function(e) {
    var data = $(".select2 option:selected").text();
    $("#test").val(data);
  });

});
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<p>select2 select box:</p>
<p>
    <select  class="select2" style="width:300px">
        <option> </option>
        <option value="AL">Alabama</option>
        <option value="VT">Vermont</option>
        <option value="VA">Virginia</option>
        <option value="WV">West Virginia</option>
    </select>
</p>

<input type="text" id="test">