如何使用从Select2下拉列表中选择的选项触发jQuery?

时间:2016-12-29 04:37:04

标签: javascript jquery jquery-select2 select2 jquery-select2-4

我正在使用Select2作为我的下拉样式。然后输出选项,如

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

我想要做的是当有人点击其中一个选项时,会触发jQuery操作loadMap(coords)。所以基本上如果有人选择第一个选项,它应该触发loadMap(001,100)

我将如何实现这一目标? https://select2.github.io/examples.html的文档说:

&#34; select2:只要选择了结果就会触发选择。&#34;

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

但是我如何才能启动jQuery操作呢?

这是我的标记:

<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 个答案:

答案 0 :(得分:3)

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

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

function loadMap(val){  
  alert("You have selected "+val);
}
&#13;
<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>
&#13;
&#13;
&#13;

你正在寻找这样的东西吗? ?