如何获取jQuery中的select2元素的最后选择或未选择的元素?

时间:2019-06-12 14:08:03

标签: jquery jquery-select2

我想获取我的select2的最后一个被选择或未被选择的元素。我遵循了官方文档,但没有任何反应。这是我的代码:

jQuery(document).ready(function() {
        Main.init();
        var $eventSelect = $('.search-select'); //select your select2 input
        $(".search-select").select2({
            allowClear: true
        });
        $eventSelect.on('select2:unselect', function(e) {
          console.log('unselect');
          console.log(e.params.data.id); //This will give you the id of the unselected attribute
          console.log(e.params.data.text); //This will give you the text of the unselected text
        })
        $eventSelect.on('select2:select', function(e) {
          console.log('select');
          console.log(e.params.data.id); //This will give you the id of the selected attribute
          console.log(e.params.data.text); //This will give you the text of the selected
        })
        $(".search-select").on('select2:select', function(e) {
            console.log(e.params.data.id);
        });
    });


 <select id="bird_id_1" name="bird_id_1[]" class="form-control search-select selects" multiple required>

 @foreach($birds as $bird)                                                   
     <option value="{{ $bird->id }}" {{ in_array($bird->id, App\Http\Controllers\ClaimController::getbirdsids($claim->id)) ? 'selected' : '' }}>{{ $bird->title_fr }}</option>                                           
 @endforeach

 </select>

1 个答案:

答案 0 :(得分:0)

这是使所有功能正常工作的最终代码。

$("select.selects").on("select2-selecting", function (e){
        console.log(e.object.text);
        $(".input_nb:last").after("<label class='"+e.val+" input_nb'>Le nombre d’oiseau pour:"+e.object.text+"</label><input type='text' class='form-control input_nb "+e.val+"' name='num_espece[]'   placeholder=''>");   
    });
    $("select.selects").on("change", function (e){
        console.log(e.removed.id)
        if(e.removed)
        {
            $("."+e.removed.id).remove();
        }

    });