Preselecting values from a multiple-select Rails form using select2 - ruby-on-rails

I'm trying to get values pre-selected in a multi-select Rails 4 form that uses select2.
The entry looks like:
- bol_selected = segments.map { |bol| seg = Bol.find_by(id: bol.to_i); [seg.bl_number, seg.id] }
= f.select :bol, options_for_select(bol_selected, bol_selected), {}, multiple: true, size: 10, id: 'bol-multiple', class: 'form-control'
It is my understanding that options_for_select takes a list of options and values as its first parameter and the pre-selected options as its second parameter, which is exactly what I have above.
I am trying this along with the following js code:
$('#bol-multiple').select2({
theme: 'bootstrap',
allowClear: true,
dropdownParent: $('#bol-multiple').parent(),
minimumInputLength: 1,
ajax: {
url: '/autocomplete/bols.json',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
q: term
};
}
}
});
The HTML this generates is as follows:
<select multiple="" id="bol-multiple" class="form-control select2-hidden-accessible" name="cargo[bol_segments][]" tabindex="-1" aria-hidden="true"
<option value="25285">ZZMUM58</option>
</select>
as per some other SO threads I've also tried adding
data: [{id: 123, text: 'Some text'}]
to the above JavaScript but this doesn't seem to pre-select any entries, it only pre-populates multi-select dropdown with some values.
Just to make it clear - the AJAX call works fine and selecting multiple values also works fine. All I'm trying to do now is get certain values pre-selected in the input field.
Thanks in advance!

Related

Choosing Option In Ajax-based Select2 From JS

I am using select2 4.0.0 for this project. A lot of the other comments and thoughts on this issue seem be for previous versions of select2, so I decided to post a new question.
I have a select2 on a page that can both create entries in the database and edit entries in the database. The select2 is populated dynamically by ajax after the user types a few letters and they can select a value. This works fine for creating entries when they need to select one.
On the same page, they can click existing entries to display further information and edit the entry in the same form. This also needs to update the select2 element with the correct selection text and update the select element that is backing the select2. Since this is normally done through ajax, the markup doesn't exist normally.
I've tried reading the documentation for select2, but I find it a bit disorganized. Does select2 provide any feature for accomplishing this? Do I need to create and update all the markup manually? I had looked at a dataAdapter, but I'm not sure if that is what I need or not.
HTML:
<select class="form-control" name="entry" id="select_field" data-url="/entry/search"></select>
Code for the select2 element:
$("#select_field").select2({
placeholder: "Search",
minimumInputLength: 2,
allowClear: true,
ajax: {
cache: true,
delay: 250,
method: 'POST',
url: $("#select_field").data('url'),
processResults: function (data, page) {
return {
results: data,
};
},
},
escapeMarkup: function (markup) { return markup; },
templateSelection: function (record) {
if (!record.id) { return record.text; }
return record.title;
},
templateResult: function (record) {
if (record.loading) { return record.text; }
var markup = $("<div>").text(record.title);
return markup.html();
},
});

Bootstrap Select2 version 3.5.2

Can anyone help me with an working example of below scenario?
Select2 option with loading data through array with default selected value and in case of edit mode changing the selected value according to users requirement. This is my code but it is not working.
<input type="hidden" id="selectCountry" class="selectCountry" style="width:100%" />
JS
var displayOptions = [{id:'1',text:'test'},{id:'2',text:'test1'},
{id:'3',text:'test2'},{id:'4',text:'test3'},
{id:'5',text:'Do not display'}]
$(".selectDisplayOptions").select2({
data: displayOptions,
minimumResultsForSearch: -1,
dropdownAutoWidth: true
});
I tried initselection but it cause problem when I try to selected different value in edit case of my application.
JS code for selecting different value in case of edit
$('.selectDisplayOptions').val(2);
You should call your select class or ID look the documentation:
https://select2.github.io/examples.html
And you should take care the way that you use to set the value in your select example:
<select class="selectDisplayOptions">
<option value="0">Boy</option>
<option value="1">Girl</option>
</select>
$('.selectDisplayOptions').val('1'); // This will bring back Girl.
$('.selectDisplayOptions').val('Girl'); // This will bring back Girl too.
var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: data
})
$(".js-example-data-array-selected").select2({
data: data
})
<select class="js-example-data-array-selected"></select>
<select class="js-example-data-array-selected">
<option value="2" selected="selected">duplicate</option>
</select>
Regards,

Select2 JSON Format for tree structure using ajax

I am trying to develop tree structure using jquery select2 plugin with ajax call that returns json format.I implemented it using struts 2.
my code is as follows
In script section
<script>
$(document).ready(function(){
var id=1;
$('#sub_lessons').select2({
minimumInputLength: 3,
maximumSelectionSize: 1,
multiple: true,
ajax: {
url: 'getData.action?lid='+id,
dataType: 'jsonp',
quietMillis: 100,
data: function(term, page) {
return {
q: term,
page_limit: 10,
page: page
};
},
results: function(data, page) {
return {
results: data,
more:false
};
}
},
formatResult: function(data) {
return data.text;
},
formatSelection: function(data) {
return data.text;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) {
return m;
}
});
});
</script>
and in body part
<select id="sub_lessons" class="form-control select2" multiple>
</select>
Here the action is not being called . If The action calls it retuns the following json String
[{"children":[{"children":[{"children":[],"id":15,"text":"algebra 3"}],"id":3,"text":"one one one"}],"id":1,"text":"another ones"},{"children":[{"children":[],"id":14,"text":"ratios"}],"id":6,"text":"lesson one"},{"children":[],"id":8,"text":"one 1"},{"children":[],"id":12,"text":"algebra 2"},{"children":[],"id":13,"text":"lesson 2"},{"children":[],"id":16,"text":"lesson 232"}]
The action is not being called. json format displays in select box something like
1
1.1
1.1.1
1.2
1.2.1
1.2.2
1.3
1.4
Now i want to implement the same using select 2 plug in.
is it possible to possible to do so?
if so please help me to implement this. I could not understand where I am doing wrong.
any help would be appreciated.
It's seems like only the following style ,
http://jsbin.com/wicutoti/20/edit
and i found some topic related to how to customising select2's dropdown
https://groups.google.com/forum/#!msg/select2/S0b-JJJIFYY/il-MYOFdGusJ
it points to not support the tree structure at present
In that thread, about trees: "not yet, something im working on for 4.0". And then: "Support for trees has probably been shelved for 4.0", says Igor and Kevin, the main Select2 developers (it seems, looking at the GitHub stats).

Select2 - Textfield instead of dropdown

I'm using Select2 with dynamic ajax loading/filtering.
What i want is a textfield like the one you can see under "Multi-Value Select Boxes" here:
http://ivaynberg.github.io/select2/
But all i get is a dropdown. This is part of my code:
= f.input_field :community, :class => :communities
$(".communities").select2({
allowClear:true,
ajax: {
...
},
formatResult: formatResult,
formatSelection: formatResult
});
What do i have to do to get a textfield instead of a dropdown?
I think createSearchChoice is the function you need.
read more at select2 search for createSearchChoice
$(".communities").select2({
createSearchChoice(term)
});
You can try this :
$('.communities').select2({
width: '100%',
allowClear: true,
multiple: true,
ajax: {
...
},
});

jquery Select2 Ajax - How set value (initSelection)

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); });
}
},
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.

Resources