2016-12-29 81 views
2

我使用Select2作为我的下拉式样。选项然后输出像如何使用从Select2下拉列表中选择的选项来启动jQuery?

<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处的文档说:

“select2:select在选择结果时触发。”

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> 

回答

3

$("#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>

您正在寻找这样的事情? ?

相关问题