select2使用jquery动态更改值

时间:2021-03-15 20:34:19

I have searched many answers and tried them but i am not able to change the value of select2 dropdown dynamically using jquery.

我已经搜索了许多答案并尝试了它们,但我无法使用jquery动态更改select2下拉列表的值。

I am using the ajax select2 getting the data remotely using json.

我正在使用ajax select2使用json远程获取数据。

dropdown is working fine.

下拉工作正常。

Here is what i have tried so far.

这是我到目前为止所尝试的。

//UserGroupID is a variable contains the database value
var groupSelector = $("#EditSpeciality");
//1.
groupSelector.select2("val", {ID: userGroupID, TEXT: "Lorem Ipsum"});
//2.
groupSelector.val(userGroupID).trigger("change");
//3.
groupSelector.select2("val", {ID: userGroupID, TEXT: "Lorem Ipsum"});
//4.
groupSelector.val(userGroupID);

But none of them seems to be changing the dropdown value.

但它们似乎都没有改变下拉值。

How to dynamically set the value..

如何动态设置值..

Here is my HTML.

这是我的HTML。

<select class="form-control select2" id="groupSelector" name="groupSelector" style="width: 100%;"></select>

=-=-=-=-=-=-=-=-=-=-=

Update:

Im using codeigniter MVC, i know this should not matter. but want to put everything on the table here.

我使用codeigniter MVC,我知道这应该不重要。但是想把所有东西放在桌子上。

The version of select2 is 4.0.0

select2的版本是4.0.0

JSON code that i am getting is from Controller through which select2 is populating the list.

我得到的JSON代码来自Controller,select2正在填充列表。

Below is select2 Code.

以下是select2 Code。

function commonSelect2(selector,url,minInputLength,placeholder){
    selector.select2({
        minimumInputLength:minInputLength,
        placeholder:placeholder,
        ajax: {
            url: url,
            dataType: "json",
            delay: 250,
            data: function (params) {
                return {
                    q: params.term, // search term
                    page: params.page
                };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function(obj) {
                        return { id: obj.ID, text: obj.TEXT };
                    })
                };
            },
            cache: true
        },
        debug:false
    });
}

i call the above function like this to initilize the dropdown in page.

我调用上面这样的函数来初始化页面中的下拉列表。

 // Speciality Selector for editing popup box
var SelectorSpeciality = $("#EditSpeciality");
var minInputLength = 0;
var placeholder = "Select Speciality";
var ConsultantSelectorURL = "' . base_url() . 'Admin/select_speciality";
commonSelect2(SelectorSpeciality,ConsultantSelectorURL,minInputLength,placeholder);

the function resides in some .js file under assets/js directory.

该函数驻留在assets / js目录下的某个.js文件中。

it helps me have the clean code and call the function whenever i want function.

它帮助我拥有干净的代码,并在需要功能时调用该函数。

i think we can fix it with initselection but i don't know how to fix it with initselection i also did tried googling it but had no luck..

我认为我们可以用initselection修复它,但我不知道如何用initselection修复它我也试过谷歌搜索但没有运气..

4 个解决方案

#1


5  

As long as the option is appended to the list first, the second option will work (for select2 4.0)

只要该选项首先附加到列表,第二个选项将起作用(对于select2 4.0)

$("#groupSelector").append ('<option value="' + userGroupID+ '">' + userGroupID+ '</option>')

groupSelector.val(userGroupID).trigger("change"); 

If you need the option to be selected this has to be done when appending,

如果您需要选择该选项,则必须在追加时执行此操作,

$("#groupSelector").append ('<option selected="selected" value="' + userGroupID+ '">' + userGroupID+ '</option>')

and the trigger change isn't needed

并且不需要触发更改

#2


2  

The second method you tried works, you just set the value of the select and then trigger a change event so select2 picks up on it:

您尝试的第二种方法有效,您只需设置选择的值,然后触发更改事件,以便select2选择它:

jQuery(function($) {
  $('select').select2();

  $('select').val(2).trigger('change');
  $('body').append('<p>Value is: ' + $('select').val() + '</p>');

  $('select').val(3).trigger('change');
  $('body').append('<p>Value is: ' + $('select').val() + '</p>');
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>

<select class="form-control select2" id="groupSelector" name="groupSelector" style="width: 100%;">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

#3


1  

You can try like this it works in my case,

您可以尝试这样,它适用于我的情况,

groupSelector.select2("val", {"id": userGroupID, text: "Lorem Ipsum"}, true);

#4


0  

Looking at these three lines

看着这三条线

var SelectorSpeciality = $("#EditSpeciality");

var SelectorSpeciality = $(“#EditSpeciality”);

groupSelector.val(userGroupID).trigger("change");

<select class="form-control select2" id="groupSelector" name="groupSelector" style="width: 100%;"></select>`

Where did #EditSpeciality come from? As far as I see, the ID is meant to be #groupSelector on that specific select that you're trying to change. Not sure where the other ID came from. Swap

#EditSpeciality来自哪里?据我所知,ID在您尝试更改的特定选择上是#groupSelector。不确定其他ID的来源。交换

var SelectorSpeciality = $("#EditSpeciality");

var SelectorSpeciality = $(“#EditSpeciality”);

To

var SelectorSpeciality = $("#groupSelector");

var SelectorSpeciality = $(“#groupSelector”);

Then see if any of the other methods mentioned in your post work.

然后看看你的帖子中提到的任何其他方法是否有效。

#1


5  

As long as the option is appended to the list first, the second option will work (for select2 4.0)

只要该选项首先附加到列表,第二个选项将起作用(对于select2 4.0)

$("#groupSelector").append ('<option value="' + userGroupID+ '">' + userGroupID+ '</option>')

groupSelector.val(userGroupID).trigger("change"); 

If you need the option to be selected this has to be done when appending,

如果您需要选择该选项,则必须在追加时执行此操作,

$("#groupSelector").append ('<option selected="selected" value="' + userGroupID+ '">' + userGroupID+ '</option>')

and the trigger change isn't needed

并且不需要触发更改

#2


2  

The second method you tried works, you just set the value of the select and then trigger a change event so select2 picks up on it:

您尝试的第二种方法有效,您只需设置选择的值,然后触发更改事件,以便select2选择它:

jQuery(function($) {
  $('select').select2();

  $('select').val(2).trigger('change');
  $('body').append('<p>Value is: ' + $('select').val() + '</p>');

  $('select').val(3).trigger('change');
  $('body').append('<p>Value is: ' + $('select').val() + '</p>');
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>

<select class="form-control select2" id="groupSelector" name="groupSelector" style="width: 100%;">
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
</select>

#3


1  

You can try like this it works in my case,

您可以尝试这样,它适用于我的情况,

groupSelector.select2("val", {"id": userGroupID, text: "Lorem Ipsum"}, true);

#4


0  

Looking at these three lines

看着这三条线

var SelectorSpeciality = $("#EditSpeciality");

var SelectorSpeciality = $(“#EditSpeciality”);

groupSelector.val(userGroupID).trigger("change");

<select class="form-control select2" id="groupSelector" name="groupSelector" style="width: 100%;"></select>`

Where did #EditSpeciality come from? As far as I see, the ID is meant to be #groupSelector on that specific select that you're trying to change. Not sure where the other ID came from. Swap

#EditSpeciality来自哪里?据我所知,ID在您尝试更改的特定选择上是#groupSelector。不确定其他ID的来源。交换

var SelectorSpeciality = $("#EditSpeciality");

var SelectorSpeciality = $(“#EditSpeciality”);

To

var SelectorSpeciality = $("#groupSelector");

var SelectorSpeciality = $(“#groupSelector”);

Then see if any of the other methods mentioned in your post work.

然后看看你的帖子中提到的任何其他方法是否有效。