在select2中添加带有文本的图像 [英] Add images with text in select2

查看:309
本文介绍了在select2中添加带有文本的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我正在创建一个带有国家名称作为选项的选择标签下拉列表,我想在其中添加受尊敬的国家/地区标志: 我用了这个HTML

Well I am creating a select tag drop down with countries name as option and i want to add the respected countries flag with them: I used this HTML

    <div class="form-group" id="abc">
        <label class="col-md-2 control-label">Language: </label>
    <div class="col-md-6">
        <select class="select2me form-control" name = "locale" id="select_lang">
            @foreach($languages as $lang)
                <option value="{{$lang->locale}}" @if($lang->locale == $company->locale) selected="selected" @endif>{{$lang->language}}</option>
            @endforeach
        </select>
    </div>

已使用JAVASCRIPT:

JAVASCRIPT USED:

    jQuery(document).ready(function() {
          $.fn.select2.defaults.set("theme", "bootstrap");
          $('.select2me').select2({
             placeholder: "Select",
             width: '100%',
             allowClear: false
           });
     function format(state) {
                if (!state.id) return state.text; // optgroup
                return "<img class='flag' src='" + MyFILEPATH() + "flags/" + state.id.toLowerCase() + ".png'/>&nbsp;&nbsp;" + state.text;
            }
            $("#select_lang").select2({
                placeholder: "Select a Country",
                allowClear: true,
                formatResult: format,
                formatSelection: format,
                escapeMarkup: function (m) {
                    return m;
                }
            });
    });

推荐答案

我对此进行了尝试,并且效果很好:

I Tried this and this is working fine:

$("#select_lang").select2({
    placeholder: "Select a Country",
    allowClear: true,
    templateResult: format,
    templateSelection: format,
    escapeMarkup: function (m) {
    return m;
  }
});

请尝试使用templateResult和templateSelection而不是formatResult和formatSelection

Please try use templateResult and templateSelection instead of formatResult and formatSelection

这篇关于在select2中添加带有文本的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆