2
votes

I am using Select2 for my dropdown styling. The options are then output like

<option value="001,100">Option 001</option>
<option value="002,200">Option 002</option>
<option value="003,300">Option 003</option>

What I want to do is that when someone clicks one of the options, the jQuery action loadMap(coords) is fired. So basically if someone selects the first option, it should fire loadMap(001,100).

How would I achieve this? The docs at https://select2.github.io/examples.html say that:

"select2:select is fired whenever a result is selected."

var $eventLog = $(".js-event-log");
var $eventSelect = $(".js-example-events");
$eventSelect.on("select2:select", function (e) { log("select2:select", e); });

But how would I get this to launch a jQuery action?

This is my markup:

<div class="form-group">
<select class="map form-control" name="map"></select>
</div>

<script>
$( document ).ready(function() {

$( ".map" ).select2({        
    ajax: {
        url: "https://www.url.com/query_maps.php",
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
                q: params.term
            };
        },
        processResults: function (data) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
            return {
                results: data
            };
        },
        cache: true
    },
    minimumInputLength: 2,
    placeholder: "Select your map"
});

});
</script>
1

1 Answers

3
votes

$("#map").select2();

$("#map").on('change', function(){
    var selected = $(this).val();
    loadMap(selected);
});

function loadMap(val){  
  alert("You have selected "+val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/>

<select id="map" class="map" style="width:300px">
   <option value="-- Select Your option --">-- Select Your option --</option>
   <option value="001,100">Option 001</option>
   <option value="002,200">Option 002</option>
   <option value="003,300">Option 003</option>
</select>

Are you looking for something like this ? ?