jQuery 使用 Select2 和 Ajax 设置加载时的初始值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18699641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:15:51  来源:igfitidea点击:

Setting initial values on load with Select2 with Ajax

jqueryajaxjquery-select2

提问by Ravi

I have select2 controls set up with Ajax (have both single and multiple). I'm trying to have some values on page load but I'm not able to get this to work however. My code for select2 is given below:

我有使用 Ajax 设置的 select2 控件(有单个和多个)。我正在尝试在页面加载时设置一些值,但是我无法使其正常工作。我的 select2 代码如下:

function AjaxCombo(element, url, multival ){  // multival = true or false
  multival = multival || false;
  $(element).select2({
   minimumInputLength: 2,
   multiple: multival,
   separator: '|',
   ajax: {
     url: url,
     dataType: 'json',
     data: function (term, page) {
        var targetname = $(this).attr('name');
        var target = targetname.slice(targetname.indexOf("[")+1, targetname.indexOf("]"));
       return {
         targettype: "search",
         target: target,
         search: term
       };
     },
     results: function (data, page) {
       return { results: data };
     }
   }
 });
}
AjaxCombo(".ajaxselect", "includes/linkedcontrol.php", false);
AjaxCombo(".ajaxmultiselect", "includes/linkedcontrol.php", true);

The Ajax combo works fine, am having trouble only with the initial values load. I tried this code below but couldn't get it to work:

Ajax 组合工作正常,只是在加载初始值时遇到问题。我在下面尝试了此代码,但无法使其正常工作:

initSelection : function (element, callback) {
    var elementText = $(element).attr('data-initvalue');
    callback(elementText);
}

My HTML from php is returned as below :

我从 php 返回的 HTML 如下所示:

<input name='header[country]' class='ajaxselect'  data-initvalue='[{"id":"IN","name":"India"}]' data-placeholder='Select Country' value='' />

I see that values are populated from php, only my jquery is having issues. My values in the control show up as US | United States of America. I guess I have edited the select2 source for getting this format as default without using format option.

我看到值是从 php 填充的,只有我的 jquery 有问题。我在控件中的值显示为US | United States of America. 我想我已经编辑了 select2 源,以便在不使用格式选项的情况下将这种格式设为默认值。

Can anyone please help me populate the default values? Thanks in advance.

任何人都可以帮我填充默认值吗?提前致谢。

EDIT:This question pertains to Select2 version <4.0. This option is removed from v4.0 and is much simpler now.

编辑:这个问题属于 Select2 版本 <4.0。此选项已从 v4.0 中删除,现在更加简单。

采纳答案by user1983983

The function which you are specifying as initSelectionis called with the initial valueas argument. So if valueis empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]'instead of data-initvaluethe function gets called and the selection can get initialized.

您指定的函数initSelection以初始value作为参数调用。因此,如果value为空,则不会调用该函数。
当您指定value='[{"id":"IN","name":"India"}]'而不是data-initvalue函数被调用并且选择可以被初始化时。

回答by JD - DC TECH

Maybe this work for you!! This works for me...

也许这对你有用!!这对我有用...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection

很好地检查代码拼写是否正确,我的问题出在initSelection,我有initselection

回答by MKK

Updatedto new version:

更新到新版本:

Try this solution from here http://jsfiddle.net/EE9RG/430/

从这里尝试这个解决方案http://jsfiddle.net/EE9RG/430/

$('#sel2').select2({
multiple:true,
ajax:{}}).select2({"data": 
     [{"id":"2127","text":"Henry Ford"},{"id":"2199","text":"Tom Phillips"}]});

回答by Lazaro Fernandes Lima Suleiman

Ravi, for 4.0.1-rc.1:

Ravi,对于 4.0.1-rc.1:

  1. Add all <option>elements inside <select>.
  2. call $element.val(yourarray).trigger("change");after select2init function.
  1. 添加<option>里面的所有元素<select>
  2. 调用$element.val(yourarray).trigger("change");select2初始化函数。

HTML:

HTML:

<select name="Tags" id="Tags" class="form-control input-lg select2" multiple="multiple">
       <option value="1">tag 1</option>
       <option value="2">tag 2</option>
       <option value="3">tag 3</option>
 </select>

JS:

JS:

var $tagsControl = $("#Tags").select2({
        ajax: {
            url: '/Tags/Search',
            dataType: 'json',
            delay: 250,
            results: function (data) {
                return {
                    results: $.map(data, function (item) {
                        return {
                            text: item.text,
                            id: item.id
                        }
                    })
                };
            },
            cache: false
        },
        minimumInputLength: 2,
        maximumSelectionLength: 6
    });

    var data = [];
    var tags = $("#Tags option").each(function () {
        data.push($(this).val());
    });
    $tagsControl.val(data).trigger("change");

This issue was reported but it still opened. https://github.com/select2/select2/issues/3116#issuecomment-146568753

已报告此问题,但它仍然打开。 https://github.com/select2/select2/issues/3116#issuecomment-146568753

回答by Daniel Díaz Astudillo

A very weird way for passing data. I prefer to get a JSON string/object from server and then assign values and stuff.

一种非常奇怪的数据传递方式。我更喜欢从服务器获取 JSON 字符串/对象,然后分配值和内容。

Anyway, when you do this var elementText = $(element).attr('data-initvalue');you're getting this [{"id":"IN","name":"India"}]. That result you must PARSE it as suggested above so you can get the real vales for id ("IN") and name("India"). Now there are two scenarios, multi-select & single-value Select2.

无论如何,当你这样做时,var elementText = $(element).attr('data-initvalue');你会得到这个[{"id":"IN","name":"India"}]。该结果您必须按照上面的建议对其进行解析,以便您可以获得 id ("IN") 和 name("India") 的真实值。现在有两种场景,多选&单值Select2。

Single Values:

单一值:

$(element).select2({
    initSelection : function (element, callback) {
        var data = {id: "IN", text: "INDIA"};
        callback(data);
    }//Then the rest of your configurations (e.g.: ajax, allowClear, etc.)
});

Multi-Select

多选

$("#tags").select2({
    initSelection : function (element, callback) {
        var countryId = "IN"; //Your values that somehow you parsed them
        var countryText = "INDIA";

        var data = [];//Array

        data.push({id: countryId, text: countryText});//Push values to data array


        callback(data); //Fill'em
    }
});

NOW HERE'S THE TRICK! Like belov91 suggested, you MUST put this...

现在是诀窍!就像 belov91 建议的那样,你必须把这个...

$(element).select2("val", []);

Even if it's a single or multi-valued Select2. On the other hand remember that you can't assign the Select2 ajax function to a <select>tag, it must be an <input>.

即使它是单值或多值 Select2。另一方面请记住,您不能将 Select2 ajax 函数分配给<select>标签,它必须是<input>.

Hope that helped you (or someone).

希望对您(或某人)有所帮助。

Bye.

再见。

回答by belov91

I`ve added

我已经添加

initSelection: function (element, callback) {

      callback({ id: 1, text: 'Text' });
}

BUT also

但是也

.select2('val', []);

at the end.

在末尾。

This solved my issue.

这解决了我的问题。

回答by gabisajr

var elem = $("#container").find("[name=elemMutliOption]");
for (var i = 0; i < arrDynamicList.length; i++)
{
   elem.find("option[value=" + arrDynamicList[i] + "]").attr("selected", "selected");
}
elem.select2().trigger("change");

This will work for people who are using the same view for multiple section in the page, with that being said it will work the same way for auto-setting defaults in your page OR better a EDIT page.

这适用于对页面中的多个部分使用相同视图的人,据说它会以相同的方式在您的页面中自动设置默认值或更好的 EDIT 页面。

The "FOR" goes through the array that has existing options already loaded in the DOM.

“FOR”遍历具有已加载到 DOM 中的现有选项的数组。

回答by Harry Bosh

Change the value after the page loads

页面加载后更改值

$('#data').val('').change();

$('#data').val('').change();

回答by Mahfuzur Rahman

Late :( but I think this will solve your problem.

迟到了 :( 但我认为这会解决你的问题。

 $("#controlId").val(SampleData [0].id).trigger("change");

After the data binding

数据绑定后

 $("#controlId").select2({
        placeholder:"Select somthing",
        data: SampleData // data from ajax controll
    });
    $("#controlId").val(SampleData[0].id).trigger("change");

回答by Jonas Sciangula Street

In my case the problem was rendering the output.. So I used the default text if the ajax data is not present yet.

在我的情况下,问题是呈现输出..所以如果 ajax 数据尚不存在,我使用默认文本。

  templateSelection: function(data) {
    return data.name || data.element.innerText;
  }