[英]How do I fire a jQuery with an option selected from a Select2 dropdown?
I am using Select2 for my dropdown styling. 我将Select2用于下拉样式。 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. 我想做的是,当有人单击选项之一时,将触发jQuery动作
loadMap(coords)
。 So basically if someone selects the first option, it should fire loadMap(001,100)
. 因此,基本上,如果有人选择了第一个选项,则应触发
loadMap(001,100)
。
How would I achieve this? 我将如何实现? The docs at https://select2.github.io/examples.html say that:
https://select2.github.io/examples.html上的文档说:
"select2:select is fired whenever a result is selected." “无论何时选择结果,都会触发select2:select。”
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? 但是,我将如何启动jQuery操作呢?
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>
$("#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 ? 您是否正在寻找这样的东西? ?
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.