Select2 - Textfield instead of dropdown - ruby-on-rails

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

Related

Preselecting values from a multiple-select Rails form using select2

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!

select2 add option with ajax enabled

I have this select2:
$('#order_address_select').select2({
placeholder: "Sratr typing...",
ajax: {
url: 'mysite/myurl',
dataType: 'json',
},
tags: true,
});
And then I am trying to add options dynamically
var newOption = new Option('myoption',1,false,false);
$('#order_address_select').append(newOption).trigger('change');
$('#order_address_select').select2('open');
new option appends in my <select></select> tag, but nothing appears in dropdown list. How do I resolve this?

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 datepicker is appending one by one for 2 fields at a time

In rails 3.2.9, I am using bootstrap's datepicker to display the date. In a single form, I need to display datepicker for 2 fields.
If I click first field then datepicker will popup. After that if I click 'tab' button then it will popup the second field's datepicker by appending to the first datepicker.
I need to display one datepicker at a time for particular field's onclick. If I click 'tab' button then first field's datepicker should be hidden and the second field's datepicker should popup.
Javascript is like below
function currentDatePicker(id){
var nowTemp = new Date();
var now = new Date(nowTemp.getFullYear(), nowTemp.getMonth(), nowTemp.getDate(), 0, 0, 0, 0);
$('#' + id).datepicker({
format: "yyyy-mm-dd",
onRender: function(date) {
return date.valueOf() < now.valueOf() ? 'disabled' : '';
}
});
}
In views,
<%= f.input :start_date, :as=>:string, :label =>"Start Date", :required => false,
:input_html=>{:readonly=>true, :value=>#user.start_date.blank? ? "" : #user.start_date} %>
<%= f.input :end_date, :as=>:string, :label =>"End Date", :required =>false,
:input_html=>{:readonly=>true, :value=>#user.end_date.blank? ? "" : #user.end_date} %>
<script type="text/javascript">
currentDatePicker('user_start_date');
currentDatePicker('user_end_date');
</script>
Above I have added an image for more information. Please help me to solve this issue.
You can use different ids for date picker and then use event handling on ids. Hide manualy first datepicker when clicked on 2nd datepicker.
Or use autoclose attribute of datepicker.
$('#from').datepicker( { autoclose: true, startDate: today.getDate.toString() } );
$('#to').datepicker( { autoclose: true, startDate: today.getDate.toString() });
form and #to are ids.
I ran into the exact same issue. I solved it by doing the following:
var pickers = $(".datepicker")
.datepicker({
format: "mm/dd/yy",
autoclose: true
})
.on("show", function(e){
pickers.not(e.currentTarget).datepicker("hide");
});

Update another control after successful jeditable submit

I am using jEditable to update a value on my MVC model and back to the database successfully. The updated value appears on the webpage which is exactly what I want. I also want to update another control on the page (as it is a calculated value using the updated field). What is the best way to do this? Is there a hook into a successful jEditable update that I can add some jQuery into to refresh the other control?
My jEditable call :
$(function () {
$(".editable_textarea").editable("#Url.Action("UpdateSharePrice","Home")", {
indicator: "<span style='color:#FF0000;'>Saving...</span>",
type: 'text',
submitdata: { _method: "put" },
select: true,
submit: 'OK',
cancel: 'X',
width: '40',
cssclass: "editable",
tooltip: 'click to edit...',
onblur: "submit"
});
});
Thanks
Colin.
Well, I figured it out in the end
You can use the JEditable callback method to get the parameters used to call the controller method:
$(function () {
$(".editable_textarea").editable("#Url.Action("UpdateSharePrice","Home")", {
indicator: "<span style='color:#FF0000;'>Saving...</span>",
type: 'text',
select: true,
submit: 'OK',
cancel: 'X',
width: '40',
cssclass: "editable",
tooltip: 'click to edit...',
onblur: "submit",
callback: function(value, settings)
{
var fundId = this.id;
$.ajax({
url: '#Url.Action("GetMarketValue", "Home")',
type: 'POST',
data: { id : fundId },
success: function (data) {
$('#marketValueDiv_' + fundId).html(data);
}
});
}
});
});
This parameter can then be used to do an ajax post to another action method that returns the calculated field from the model:
public ActionResult GetMarketValue(int id)
{
if (ModelState.IsValid && id > 0)
{
BaseFund targetFund = _context.Funds.Find(id);
return PartialView("GetMarketValue", targetFund);
}
else
{
return PartialView("0.00");
}
}
The success callback on the ajax call is then used to update the appropriate div html content

Resources