9

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

I am using the ajax select2 getting the data remotely using 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.

<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.

The version of select2 is 4.0.0

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

Below is 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.

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..

1
  • For me it just worked changing first the select value (select.value=val;) then trigger the event to update select2 label ($select.trigger('change.select2');). Commented Mar 11 at 1:23

4 Answers 4

10

As long as the option is appended to the list first, the second option will work (for 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

Sign up to request clarification or add additional context in comments.

1 Comment

The attribute selected="selected" was missing in my case. Thanks!
3

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:

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>

1 Comment

Sir, My code has json data coming from the controller. and i am using select2 4.0.0. and none of above methods worked out for me :(
1

You can try like this it works in my case,

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

Comments

0

Looking at these three lines

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

var SelectorSpeciality = $("#EditSpeciality");

To

var SelectorSpeciality = $("#groupSelector");

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.