javascriptruby-on-railsrubyjquery-select2select2-rails

select2 multiple selections cleared on form.submit (ruby on rails)


I'm using select2 for a form submission. My html looks like this:

<%= form.select "page_request_ids", [], {}, id: "page_request_ids", multiple: true, style: "width:506px;" %>

javascript:

jQuery('select#page_request_ids').select2({
    placeholder: "Start typing paths...",
    allowClear: true,
    ajax: {
        url: "/page_requests/multiautocomplete",
        dataType: 'json',
        type: "GET",
        data: function(params) {
            return {
                option: params.term, 
            };
        },
        processResults: function(data, params) {
            return {
                results: jQuery.map(data, function(item) {
                    return {
                        text: item[0] + " (" + item[1] + ")",
                        request: item[1],
                        id: item[2]
                    }
                })
            };
        }, 
        cache: true
    }
});

When the form gets submitted the values clear the form field. I'm trying to make sure that these values appear after the form has been submitted (the same form is loaded when the form is submitted).

Any help would be awesome.


Solution

  • You need to set the page_request_ids to select tag after from submission.

    <%= form.select "page_request_ids", [], {}, id: "page_request_ids", multiple: true, style: "width:506px;" %>

    here you need to pass the your page_request_ids collection instead of blank Array.