【问题标题】:How do I fire a jQuery with an option selected from a Select2 dropdown?如何使用从 Select2 下拉列表中选择的选项触发 jQuery?
【发布时间】:2016-12-29 04:37:03
【问题描述】:

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

"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>

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 1970-01-01
      • 2018-09-26
      • 2021-12-01
      相关资源
      最近更新 更多