如何在具有select2初始化的输入框上设置默认值

时间:2022-11-27 19:27:23

How do I set default value on an input box with select2? here is my HTML

如何在带有select2的输入框上设置默认值?这是我的HTML

<input type="text" id="itemId0" value="Item no. 1">

and my javascript:

和我的javascript:

    $("#itemId0").select2({
    placeholder: 'Select a product',
    formatResult: productFormatResult,
    formatSelection: productFormatSelection,
    dropdownClass: 'bigdrop',
    escapeMarkup: function(m) { return m; },
    minimumInputLength:1,
    ajax: {
        url: '/api/productSearch',
        dataType: 'json',
        data: function(term, page) {
            return {
                q: term
            };  
        },  
        results: function(data, page) {
            return {results:data};
        }   
    }   
});

function productFormatResult(product) {
   var html = "<table><tr>";
   html += "<td>";
   html += product.itemName ;
   html += "</td></tr></table>";
   return html;
}

function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}

here is the issue: If I wont initialize my input box into a select2 box, I can display the default value of my input box which is "Item no. 1", 如何在具有select2初始化的输入框上设置默认值 but when I initialize it with select2 eg. $("#itemId0").select2({code here}); I cant then display the default value of my text box. 如何在具有select2初始化的输入框上设置默认值.

这里的问题是:如果我不将输入框初始化到select2框中,我可以显示我的输入框的默认值,即“Item no”。1",但当我用select2 eg初始化它时。$(" # itemId0”)。select2({代码});我不能显示我的文本框的默认值。

Anyone knows how can I display the default value please?

有人知道我如何显示默认值吗?

7 个解决方案

#1


18  

You need to utilize the initSelection method as described in Select2's documentation.

您需要使用Select2文档中描述的initSelection方法。

From the documentation:

从文档:

Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.

在创建Select2时调用,以允许用户根据所附的Select2元素的值初始化所选内容。

In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.

在您的示例中,请查看装载远程数据的示例,它展示了如何将其与AJAX请求合并在一起。

I hope this helps.

我希望这可以帮助。

#2


6  

Old initial selections with initSelection

旧的初始选择与initSelection。

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.

在过去,Select2需要一个名为initSelection的选项,该选项在使用自定义数据源时定义,允许对要确定的组件进行初始选择。这已被数据适配器上的当前方法所取代。

{
  initSelection : function (element, callback) {
    var data = [];
    $(element.val()).each(function () {
      data.push({id: this, text: this});
    });
    callback(data);
  }
}

You can use the set value too.

您也可以使用set值。

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

您应该直接在底层元素上调用.val。如果需要第二个参数(triggerChange),还应该在元素上调用.trigger(“change”)。

$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");

Refs:

参考文献:

#3


4  

If you have an input element, declare it as follows. Remember to populate the value field as well.

如果您有一个输入元素,声明如下。还记得填充value字段。

<input type="hidden" name="player" id="player" data-init-text="bla bla" value="bla bla" >

Write an initSelection function

写一个initSelection函数

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

make sure that this call back has same key value pair as the one return by the ajax call.

确保这个回调具有与ajax调用返回的键值对相同的键值。

callback({"text":elementText,"id":elementText});

I have noticed that keeping the value field empty will keep the input empty by default so remember to populate it as well.

我注意到,保持值字段为空将默认保持输入为空,因此请记住填充它。

#4


2  

The method initSelection can not have an empty value attribute to work properly.

initSelection方法不能有一个空值属性来正常工作。

That was my problem.

这是我的问题。

Hopefully this will help someone.

希望这能帮助到别人。

#5


1  

You can easily change the value of your select input by just putting the id's of your selected option in data attribute of your select input. And then in javascript

只需将所选选项的id放在所选输入的data属性中,就可以轻松地更改所选输入的值。然后在javascript

var select =  $('.select');
var data   =  $(select).data('val');

$(select).val(data);

And after that initialize select2 on your select input

然后在select输入上初始化select2

$(select).select2();

Here is the fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/

这是fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/

#6


0  

you dont need ajax or json, you just need to put SELETED tag into your OPTION and SELECT2 will display the init value.

您不需要ajax或json,只需将SELETED标记放入您的选项中,SELECT2将显示init值。

#7


0  

This works for me: 'Add default value to the head of array'

这适用于我:'将默认值添加到数组的头部'

data.unshift({'id':-1, 'name':'xxx'});

$('#id_xxx).select2({
      placeholder: '--- SELECT ---',
      data: data,
      allowClear: true,
      width: '100%'
});

However, official doc says:

然而,官方的医生说:

You can set default options by calling $.fn.select2.defaults.set("key", "value").

There is no example though.

但是没有例子。

#1


18  

You need to utilize the initSelection method as described in Select2's documentation.

您需要使用Select2文档中描述的initSelection方法。

From the documentation:

从文档:

Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.

在创建Select2时调用,以允许用户根据所附的Select2元素的值初始化所选内容。

In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.

在您的示例中,请查看装载远程数据的示例,它展示了如何将其与AJAX请求合并在一起。

I hope this helps.

我希望这可以帮助。

#2


6  

Old initial selections with initSelection

旧的初始选择与initSelection。

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.

在过去,Select2需要一个名为initSelection的选项,该选项在使用自定义数据源时定义,允许对要确定的组件进行初始选择。这已被数据适配器上的当前方法所取代。

{
  initSelection : function (element, callback) {
    var data = [];
    $(element.val()).each(function () {
      data.push({id: this, text: this});
    });
    callback(data);
  }
}

You can use the set value too.

您也可以使用set值。

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

您应该直接在底层元素上调用.val。如果需要第二个参数(triggerChange),还应该在元素上调用.trigger(“change”)。

$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");

Refs:

参考文献:

#3


4  

If you have an input element, declare it as follows. Remember to populate the value field as well.

如果您有一个输入元素,声明如下。还记得填充value字段。

<input type="hidden" name="player" id="player" data-init-text="bla bla" value="bla bla" >

Write an initSelection function

写一个initSelection函数

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

make sure that this call back has same key value pair as the one return by the ajax call.

确保这个回调具有与ajax调用返回的键值对相同的键值。

callback({"text":elementText,"id":elementText});

I have noticed that keeping the value field empty will keep the input empty by default so remember to populate it as well.

我注意到,保持值字段为空将默认保持输入为空,因此请记住填充它。

#4


2  

The method initSelection can not have an empty value attribute to work properly.

initSelection方法不能有一个空值属性来正常工作。

That was my problem.

这是我的问题。

Hopefully this will help someone.

希望这能帮助到别人。

#5


1  

You can easily change the value of your select input by just putting the id's of your selected option in data attribute of your select input. And then in javascript

只需将所选选项的id放在所选输入的data属性中,就可以轻松地更改所选输入的值。然后在javascript

var select =  $('.select');
var data   =  $(select).data('val');

$(select).val(data);

And after that initialize select2 on your select input

然后在select输入上初始化select2

$(select).select2();

Here is the fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/

这是fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/

#6


0  

you dont need ajax or json, you just need to put SELETED tag into your OPTION and SELECT2 will display the init value.

您不需要ajax或json,只需将SELETED标记放入您的选项中,SELECT2将显示init值。

#7


0  

This works for me: 'Add default value to the head of array'

这适用于我:'将默认值添加到数组的头部'

data.unshift({'id':-1, 'name':'xxx'});

$('#id_xxx).select2({
      placeholder: '--- SELECT ---',
      data: data,
      allowClear: true,
      width: '100%'
});

However, official doc says:

然而,官方的医生说:

You can set default options by calling $.fn.select2.defaults.set("key", "value").

There is no example though.

但是没有例子。