Search code examples
javascriptjqueryjquery-select2ajaxformjquery-select2-3

How to I add multiple records through ajaxform to a select2 form?


select2/3.5.2/

I am reposting this because my initial post wouldn't format correctly.

The following items are being used:

  1. multiple records can be searched in a select2 form field
  2. A bootstrap popup modal has a form to enter a new record if it isn't found in the select2 form.
  3. AjaxForm is used to pass the new record from the modal form to the select2 form

Issues:

  1. If a second record is added, it replaces the first record passed to the select2 field rather than appending it.
  2. When the select2 form is submitted for processing, it will pass records selected in the select2 but not added from the ajaxform (modal).
  3. The modal does not clear the form values.

I am new to js and jquery, so any help would be appreciated.

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.js"></script>

        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2-bootstrap.css">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js"></script>

        <script>
            $(document).ready(function() { 
                //select2
                $("#contact_search").select2({
                    width: '100%',
                    allowClear: true,
                    minimumInputLength: 3
                });

                // ajaxform
                $('#contactform').ajaxForm({
                    dataType: 'json',
                    success: processJson
                });

                function processJson(data) { 
                    //close the modal
                    $('#contactmodal').modal('hide');
                    // set the returned data to a variable
                    var newcontactid = data.DATA;
                    //output data to console
                    console.log(data);

                    var firstname = $('#fname').val();
                    var lastname = $('#lname').val();
                    var name = firstname + ' ' + lastname;
                    $("#contact_search").select2("data", [{id: data.DATA, text: name}]);
                };
            }); 
        </script>

Form:

<div class="row indent">
    <div class="col-md-5">
        <form name="searchform" action="ajaxform_action.cfm" method="post">
            <label>Search for People</label>

            <select id="contact_search" multiple size="50" name="people">
            <cfoutput query="people">
                <option value="#people.contactid#" >#firstname# #lastname#</option>
            </cfoutput>
            </select> 

            <input type="submit" value="Save" name="submit" class="btn btn-primary btn-xs" />
        </form>

        <!---Add New Person--->
        <a href="#newAuthorModal" data-toggle="modal" title="New Profile" data-field="contactform" data-target="#contactmodal">
            <img src="img/user_add.png" alt="Add New Person" title="Add New Person" border="0">
        </a>
    </div>
</div> 

Contact Modal

<div class="modal fade" id="contactmodal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
                </button>
            </div>
            <div class="modal-body">
                <!---Form--->
                <form id="contactform" action="cfc/insert.cfc?method=insertcontact" method="post" name="testform">
                    First Name: <input type="text" name="firstname" id="fname" /> 
                    Last Name: <input type="text" name="lastname" id="lname" />
                    <input id="btnSave" type="submit" value="Submit" /> 
                </form>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

Solution

  • Let's try and solve problems one by one.

    1. If a second record is added, it replaces the first record passed to the select2 field rather than appending it.

    The problem is in this part of your code:

    $("#contact_search").select2("data", [{id: data.DATA, text: name}]);
    

    What it does is it resets the selection, instead of appending a new item. The "append" functionality may be implemented this way:

    // get current selection
    var selection = $("#contact_search").select2("data");
    // add a new item to the selection
    selection.push({id: data.DATA, text: name});
    // set the updated selection
    $("#contact_search").select2("data", selection);
    
    1. The modal does not clear the form values.

    That's kind of expected, since you only "hide" the modal, without manipulating its underlying DOM content. This can be fixed by adjusting the processJson function to be:

    function processJson(data) { 
        //close the modal
        $('#contactmodal').modal('hide');
        // set the returned data to a variable
        var newcontactid = data.DATA;
        //output data to console
        console.log(data);
    
        var firstname = $('#fname').val();
        var lastname = $('#lname').val();
    
        // Clear the input values!
        $('#contactmodal input[type=text]').val("");
    
        // the rest of the function
        ...
    }
    

    Here's a working sample of these solutions inside a JSFiddle