jquery Select2 Ajax - How set value (initSelection)
Asked Answered
A

1

7

How set in the drop-down list item selected by the user?

Scenario:
1. User not enter all required values in form
2. Click sent.
3. Page is refresh and value in dropdown list is not selected. How select the value?

I have working script which retrieve data for the list.

$('#userid').select2({
placeholder : " --- select ---",
minimumInputLength: 2,
ajax: {
    url: "index.php?modul=getusers",
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: function (term, page) {
        return {
            q: term,
            page_limit: 10
        };
    },
    results: function (data, page) {
        return { results: data };
    }
},
allowClear: true,
formatSelection: function(data) { 
   return data.text; 
}   
});

Standard data in ajax call: {"text":"sample text", "id":"1"}

Input:

  <input type="text" value="<? echo $_POST['userid']; ?>" class="input" id="userid" name="userid"> 

I tried to add the following code, but it doesn't work

initSelection: function(element, callback) {
    var id=$(element).val();
    if (id!=="") {
       $.ajax("index.php?modul=getusersfriend&q="+id, {
       dataType: "json"
       }).done(function(data) { callback(data); });
    }
},
Accouchement answered 30/5, 2013 at 15:43 Comment(0)
C
0

Make sure that you have a properly formatted JSON Object being returned in your call back in initSelection. The discussion for that has been addressed here already.

But so far looks good. You may want to bind the change event of the select or the submit event of the form to serialize its value before the form is submitted.

You can store its value on your server (yucky) or just serialize the form object and get the value to pass to initSelection when the select2 is loaded.

Which is what would happen here:

 var id=$(element).val();

Here is a simple example of serializing your form.

PS: Don't really see what bootstrap has to do with anything.

Cyanosis answered 25/6, 2013 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.