当我更改元素选项时,如何在select2中保留选定的标记

时间:2017-01-23 02:52:37

标签: select2



import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import prefs.UserInfo;
import prefs.UserSession;


public class Login extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = Login.class.getSimpleName();
    private EditText email, password;
    private Button login;
    private TextView signup;
    private ProgressDialog progressDialog;
    private UserSession session;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        signup = (TextView) findViewById(R.id.open_signup);
        progressDialog = new ProgressDialog(this);


        session = new UserSession(this);
        userInfo = new UserInfo(this);

        if (session.isUserLoggedin()) {
            startActivity(new Intent(this, MainActivity.class));
            finish();

        }

        login.setOnClickListener(this);
        signup.setOnClickListener(this);

    }

    private void login(final String email, final String password) {
        //Tag used to cancel the request
        String tag_string_req = "req_login";
        progressDialog.setMessage("Logging in....");
        progressDialog.show();

        StringRequest strReq = new StringRequest(Request.Method.POST,
                Utils.LOGIN_URL, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Login Response: " + response.toString());

                try {
                    JSONObject jObj = new JSONObject(response);
                    boolean error = jObj.getBoolean("error");

                    //check for error node in json
                    if (!error) {
                        //now store the user in SQLite
                        JSONObject user = jObj.getJSONObject("user");
                        String uName = user.getString("username");
                        String email = user.getString("email");

                        //Inserting row in users table
                        userInfo.setEmail(email);
                        userInfo.setUsername(uName);
                        session.setLoggedin(true);

                        startActivity(new Intent(Login.this, MainActivity.class));
                        finish();
                    } else {
                        //error in login, get the error message
                        String errorMsg = jObj.getString("error_msg");
                        toast(errorMsg);
                    }
                } catch (JSONException e) {
                    //json error
                    e.printStackTrace();
                    toast("Json error: " + e.getMessage());

                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(TAG, "Login Error: " + error.getMessage());
                toast("Unknown Error occured");
                progressDialog.hide();
            }

        }) {
            @Override
            protected Map<String, String> getParams() {
                //Posting parameters to login url
                Map<String, String> params = new HashMap<>();
                params.put("email", email);
                params.put("password", password);

                return params;

            }
        };


//Adding request to request queue
        AndroidLoginController.getInstance();

        addToRequestQueue(strReq, tag_string_req);
    }

    private void toast(String x) {
        Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                String uName = email.getText().toString().trim();
                String pass = password.getText().toString().trim();

                login(uName, pass);
                break;
            case R.id.open_signup:
                startActivity(new Intent(this, SignUp.class));
                break;

        }
    }


    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Login Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }
}
&#13;
// js i call select2

$('#select-user-multiple').select2({
            closeOnSelect: false,
            tags: true,
            allowClear: true
        });

// my code to get list users by select organization and suborganization

 $('#slc-UserOrganization').change(function(){
            var parentId = $('#slc-UserOrganization').val();
            var subOrgId = $('#slc-UserSubOrganization').val();
            getListUserForSendEmail(parentId, subOrgId);
            if (parentId != -1) {
                getListSubOrganizationEmail(parentId);
            } else {
                $('#slc-UserSubOrganization').find('option').remove();
            }
        });

$('#slc-UserSubOrganization').change(function(){
            var parentId = parseInt($('#slc-UserOrganization').val(), 10);
            var subOrgId = parseInt($('#slc-UserSubOrganization').val(), 10);
            getListUserForSendEmail(parentId, subOrgId);
        });


function getListUserForSendEmail(unitId, partId) {
        $('#select-user-multiple').find('option').attr("disabled", true);
        // $('#select-user-multiple').find('option').attr("style", "display:none");
        // $('select2-select-user-multiple-results').find('li').hide();

        $.ajax({
        url : URL_vBooking,
        jsonp : "jsoncallback",
        dataType : 'jsonp',
        data : {
            _f : 122,
            unitId: unitId,
            partId: partId,
            start: 0,
            limit: 1000,
            ownerId: communityIdGlobal,
            communityId: communityIdGlobal
        },
        success: function (response) {
            if(response.success){
                $.each(response.object, function(key, value){
                    // var checkboxHtml = '';
                    // var user_community = value.community;
                    // var attendeeInfo = '{"email":"' + value.email + '", "communityId":' + value.communityId + ', "name":"' + user_community.name + '", "partId":' + value.partId + ', "unitId":' + value.unitId + '}';
                    // checkboxHtml += '<option user_id="'+ value.communityId + '" value="'+ attendeeInfo +'">'+ user_community.name +'</option>'
                      
                    // $('select#select-user-multiple').append(checkboxHtml);
                    // console.log(checkboxHtml);

                    var checkboxHtml = '';
                    var user_community = value.community;
                    var attendeeInfo = '{"email":"' + value.email + '", "communityId":' + value.communityId + ', "name":"' + user_community.name + '", "partId":' + value.partId + ', "unitId":' + value.unitId + '}';

                    checkboxHtml += "<option value='"+ attendeeInfo +"' user_id='"+ value.communityId + "'>"+ value.name +"</option>";
                      
                    $('select#select-user-multiple').append(checkboxHtml);
                });
            }
        },
        error: function(response){
            console.log("getListUserForSendEmail() ==> error:\n" + JSON.stringify(response));
        }
        });
    }
&#13;
http://stackoverflow.com/posts/41798617/edit#
&#13;
&#13;
&#13;

// my modal
<div class="modal fade" id="modalBooking" tabindex="-1" role="dialog" aria-labelledby="modalBooking">
            <div class="modal-dialog" role="document">
                <div class="modal-content" style="width: 800px;">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title">Thêm Ngư?i Tham D?</h4>
                    </div>
                    <div class="modal-body">
                        <div class="modal-body-header">
                            <div class="form-group col-sm-12">

                                <select id="slc-UserOrganization" class="form-control input-sm col-sm-4" style="text-align: center; width: 35%">
                                    <option value="-1">-----------Đơn V?-----------</option>
                                    <!-- append các đơn v? vào t?i đây -->
                                </select>
                                <div class="input-sm col-sm-4" style="width: 5%">
                                    
                                </div>
                            
                                <select id="slc-UserSubOrganization" class="form-control input-sm col-sm-4" style="text-align: center; width: 30%">
                                    <option value="-1">---Ph?ng Ban---</option>
                                    <!-- append các ph?ng ban vào t?i đây khi select đơn v?-->
                                </select>

                                <div class="input-sm col-sm-4" style="width: 15%; padding: 0px 10px;">
                                    <button class="btn-add-suborganization" onClick="addSuborganization();" style="background-color: #3c8dbc; border-color: #367fa9; color: #fff; height: 100%;">Ch?n Ph?ng</button>
                                </div>
                            </div>
                        </div>
                        <div class="form-group col-sm-12">
                            <div>
                                <label for="id_label_multiple">Danh sách thành viên</label>  
                            </div>
                              <select class="js-example-basic-multiple js-states form-control" id="select-user-multiple" multiple="multiple" style="width: 100%">
                                 
                              </select>
                            
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Quay l?i</button>
                        <button type="button" class="btn btn-primary" data-

<!-- begin snippet: js hide: false console: true babel: false -->
大家好! 我使用select2 bootraps选择并显示多个选定用户以向他们发送邮件。当我更改另外1个下拉列表时,select2中的elements选项会更改。而且,我之前选择的选定标签将被自动删除。反正我还留着他们吗?请告诉我。非常感谢。

首先,我选择了一些选项。

然后,我更改其他下拉列表,元素选项将更改,并删除选定的标签。 https://i.stack.imgur.com/nNNyX.png

0 个答案:

没有答案