【问题标题】:Select2 templateResult not working for trigger changeSelect2 templateResult 不适用于触发器更改
【发布时间】:2020-07-28 03:25:46
【问题描述】:

我正在使用 select2 4.0.5

目前,我的 select2 初始化代码如下:

/** Basic select2*/
$('.am_select2').select2({
    escapeMarkup: function (markup) {
        return markup;
    },
    templateResult: formatResult,
    templateSelection: formatResult,
    tags: true,
    createTag: function (params) {
        // Don't offset to create a tag if there is no @ symbol
        if (params.term.match(/[a-z]/i)) {
            // Return null to disable tag creation
            return {
                id: params.term,
                text: params.term +' <span class="new-category-text">Hit Enter to add as new category</span>',
                tag: true
            }
        }
        return null;
    },
    matcher: matchStart,
}).on('select2:select', function (evt) {
    if(evt.params.data.tag === true) {
        Swal.fire({
            title: 'Are you sure you want to add a new category?',
            text: "If you meant to select from a standard category then please click cancel.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Add new category'
        }).then((result) => {
            if (result.value) {
                let option = new Option(evt.params.data.text, evt.params.data.id);
                $(".am_select2").append(option);
            }else{
                let $this = $(this);
                $(this).val('').trigger('change');
            }
        });
    }

    /*Issues because of this part starts*/
    let $row = $(this).attr('data-row');
    let $selected_opt = $(this).val();

    if($('.checkbox-combo input#checkbox_'+$row+':checkbox').is(':checked')){
        let checkedArr = [];
        $(".checkbox-combo input:checkbox:checked").each(function(){
            checkedArr.push($(this).val());
        });

        $.each( checkedArr, function( key, value ) {
            $("#select2_"+value).select2().val($selected_opt).trigger("change");
        });
    }
    /*Issues because of this part ends*/
});
    function formatResult(state)
    {

        if (state.text === '-- Select --') {
            return '<span class="text-danger">'+state.text+'</span>';
        }
        if (!state.id || !state.element) {
            // console.log(state);
            return state.text;
        }

        if(state.element.dataset.global === '1'){
            console.log(state);
            return '<span>'+state.text+'</span><span class="float-right">Standard</span>';
        }else{
            return '<span>'+state.text+'</span>';
        }
    }

这在第一次加载 select2 时可以正常工作,它会根据需要显示 templateResult。但是,我已经实现了一个条件,允许用户仅通过更改单个字段来更改多个选择字段的选定选项。 此代码包含在第一个代码块中:/*Issues because of this part starts*/

ISSUE 当这个trigger('change') 被触发时,带有文本Standard 的templateResult 不会显示,它只显示普通选项(即没有文本Standard)。

您可以查看下面的代码以获取表单部分。 ($amenities 只是一个对象数组)

@foreach($amenities as $ak => $av)
<div id="row_{{$ak}}" class="form-group row">
    <label for="cat_map[]" class="col-sm-3 col-form-label required">{{ ($av != '')?$av:'(Empty Cell)' }}</label>
    <div class="col-sm-4">
        <select data-row="{{$ak}}" id="select2_{{ $ak }}" class="form-control am_select2 @error('cat_map[]') is-invalid @enderror" name="cat_map[]" required>
            <option value="" class="text-danger">{{ __('-- Select --') }}</option>
            @foreach($categories as $ck => $cv)
                <?php
                    $selected = '';
                    if($mapped_array[$ak] == $cv->id){
                        $selected = "selected";
                    }

                ?>
                <option data-global="{{$cv->global}}" value="{{$cv->id}}" {{ $selected }}>{{ $cv->category_name }} </option>
            @endforeach
        </select>
        @if($av == "")
            <small>Suggested: You may map as “Unclear” and change the mapping later by clicking “Edit Categories” from the Amenity Audit page.</small>
        @endif
        @error('cat_map[]')
        <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
        @enderror
    </div>
    <div class="col-sm-2 checkbox-combo">
        <div class="checkbox checkbox-info pl-2">
            <input name="selected_am" id="checkbox_{{ $ak }}" type="checkbox" value="{{$ak}}">
            <label for="checkbox_{{ $ak }}">
            </label>
        </div>
    </div>
</div>
@endforeach

【问题讨论】:

    标签: laravel jquery-select2 jquery-select2-4


    【解决方案1】:

    在触发时调用你的 templateResult 回调:

    $("#select2_"+value).select2({templateResult:formatResult}).val($selected_opt).trigger("change");
    

    【讨论】:

      猜你喜欢
      • 2020-04-24
      • 2020-01-02
      • 2013-04-10
      • 2021-04-15
      • 2022-10-13
      • 2018-11-13
      • 1970-01-01
      • 2013-07-23
      • 1970-01-01
      相关资源
      最近更新 更多