0

I have used the select2.js library for dropdown list in my code. I want to select the dropdown value deafult as per the value get from my url. I have no idea how to do that thing in select.js.

Here in below code var e I get the value which I want to selected. Javascript code:

 $( document ).ready(function() {
     var url = window.location.href;
     var a = url.split('=');
     var b = a[2];
     var d = b.split('_');
     var e =d[1];
     $("#Address1").select2({

        })

   }); 

HTML code:

<select class="ct-select-lg" id="Address" name="Address[]">
                            </select>

In these code i get the data from my API:

$("#Address").select2({
  ajax: {
    url: "url",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term,
        page: params.page
      };
    },
    processResults: function (data, params) {
    return {
        results: data.items,

      };
    },
    cache: true
  },
  placeholder: 'Search for a repository',
  escapeMarkup: function (markup) { return markup; },
  minimumInputLength: 1,

});
garfbradaz
  • 3,424
  • 7
  • 43
  • 70
Code ninja
  • 37
  • 1
  • 8

1 Answers1

0

As, per your last comment I hope your URL be like http://localhost/test/?test=1. So, by what I understand I created some code, this will get value from the url and then set value for the select.

    <link rel="stylesheet" href="select2-4.0.6-rc.1/dist/css/select2.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="select2-4.0.6-rc.1/dist/js/select2.js"></script>
    <script>
        var url = window.location.href;
        var selected = (url.split('?')[1]).split('=')[1]
        jQuery(document).ready(function(){
            jQuery('#select').select2();
            jQuery('#select').val(selected).trigger('change');
        })
    </script>
    <select style="width:100px;" id="select">
        <option>Select</option>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
    </select>

NOTE: You have to add path of select2 as per your local directories.

BlueSuiter
  • 527
  • 6
  • 21