Is it possible to add an option to the top of a select2 when data comes from ajax? - jquery-select2-4

I need to insert at the beginning of the list a new option in the select2 control.
I tried with
var data = {
id: -1,
text: 'SISTEMA'
};
var newOption = new Option(data.text, data.id, false, false);
$('#UsuarioId').append(newOption).trigger('change');
But that does not work when data comes from Ajax. In that case, the combobox appears with that option selected and when list is expanded, that option is not there.
Regards
Jaime

Create a variable and initially define that variable as the option you want to include - eg:
var trHTML;
trHTML = '<option value=""></option>'
Then loop through your result set adding each item back to that variable
$.each(x, function (i, item) {
trHTML += '<option value=' + value_name +'>'+ display_name +'</option>';
});
Then append the entire list to the select, and initiate Select2
$('#dropdown_name').append(trHTML);
$('#dropdown_name').select2({
placeholder: "foobar",
allowClear: true
});

This documentation from select2 already explains
https://select2.org/data-sources/ajax

Related

Get selected option in Select2 event, when multiple options can be selected

How can I get hold on the <option> that was just selected when listening to the select2:select event? Note that this is simple when using a single-select, as when only one option is selected, that must be the one that was just selected. I would like to also be able to find the option that was just selected when using a multiple-select (<select multiple>).
In the select2:unselect event, the unselected <option> is available through e.params.data.element, but it is not so in the select2:select event. I do not see a reason why the <option> should not be available, since it is created at this time. For the select2:selecting event, however, the <option> is not yet created, and obviously cannot be available when the event is fired.
I've used the following to get the current selected in Select2 (it's for version 4 and up):
// single value
var test = $('#test');
test.on("select2:select", function(event) {
var value = $(event.currentTarget).find("option:selected").val();
console.log(value);
});
UPDATE: Multi Selected Values (with and without last selected)
// multi values, with last selected
var old_values = [];
var test = $("#test");
test.on("select2:select", function(event) {
var values = [];
// copy all option values from selected
$(event.currentTarget).find("option:selected").each(function(i, selected){
values[i] = $(selected).text();
});
// doing a diff of old_values gives the new values selected
var last = $(values).not(old_values).get();
// update old_values for future use
old_values = values;
// output values (all current values selected)
console.log("selected values: ", values);
// output last added value
console.log("last added: ", last);
});
$('#test').on('select2:select', function(e) {
var data = e.params.data;
console.log(data);
});

Select2 version 4 not not able to set data / selection

I just upgraded to version 4 and now my set data is not working
I'm doing the following, which worked fine before the update
Init
$("#fertilizer").select2({
data: listToLoad,
placeholder: mf('pleaseSelectFertilizer',"please select fertilizer")
}).on('change', function (e) {
var concentration = $("#fertilizer").select2('data')[0].concentration;
$("#typesOfConcentration").text(concentration);
$("#typesOfConcentrationDiv").removeClass("hide");
});
var fertilizer = $("#orders").select2('data')[0].fertilizer;
var fertilizerId = $("#orders").select2('data')[0].id;
var concentration = $("#orders").select2('data')[0].concentration;
$("#fertilizer").select2("data", {id: fertilizerId, text:fertilizer});
As noted in the release notes (twice actually), .select2("data") is read-only now. This will actually trigger a warning if you put Select2 into debug mode (setting the option debug to true).
In your case, you don't need to use .select2('data') at all. You appear to only be using it so you can re-map fertilizer to text, which should be done way before the option is selected. The id and text properties are required and it doesn't take much to re-map them before passing data to Select2.
var listToLoad = $.map(listToLoad, function (obj) {
obj.text = obj.text || obj.fertilizer;
return obj;
});
$("#fertilizer").select2({
data: listToLoad,
placeholder: mf('pleaseSelectFertilizer',"please select fertilizer")
}).on('change', function (e) {
var concentration = $("#fertilizer").select2('data')[0].concentration;
$("#typesOfConcentration").text(concentration);
$("#typesOfConcentrationDiv").removeClass("hide");
});
For everyone else who actually used .select2('data'), you should be able to use .val() now and just pass in the id that needs to be set. If you need to select an option which doesn't actually exist, you can just create the <option> for it (like you would in a standard <select>) ahead of time.

Filtering a dropdown based on the value in another dropdown in Rails

I have a Country model. In view I have a country dropdown. If country1 is selected, all states of that country must be listed in states dropdown box. If country2 is selected, only 'others' must be displayed in the drop down box. I have jquery to do this. but how do i access a constant defined in ruby in jquery? How do I do that?
$('#country_id').change(function() {
debugger
var country = $('#country_id').val();
if (country != 'India') {
// $('#country_state').val("others");
//$('#country_state').prop("disabled", true);
$('#country_state').empty().append('<option>Other</option>');
$('#phone').focus();
}
else{
$('#country_state').empty().append('<option>indiastates*</option>');
}
})
*indiastates is a constant in ruby. How do i display that as options for dropdown?
you can try grouped_collection_select
here is the railscast http://railscasts.com/episodes/88-dynamic-select-menus-revised
For the second dropdown list, I first created an array with the values i wanted to display in the dropdown.
var states_array = new Array("xxx","yyy");
to append this into dropdown
var states_option;
for(var i=0;i<states_array.length;i++)
states_option += "<option>" + states_array[i] + "</option>";
$school_state.empty().append( states_option );

Convert Select2 input to tokens

Does the Select2 jQuery plug-in have a built-in function for converting strings to tokens?
I want to be able to call this tokenizing function when the user pastes strings into a Select2 field so that the pasted input becomes tokens.
I think I have solved the question myself with the following code:
// force tokenizing of Select2 auto-complete fields after pasting
$('body').on('paste', '.select2-input', function() {
// append a delimiter and trigger an update
$(this).val(this.value + ',').trigger('input');
});
This assumes that commas are set as delimiters in the plug-in's "tokenSeparators" initialization setting.
For 4.0.1 version:
$('#my-select').data('select2').dataAdapter.$search.val("tag1,tag2,").trigger("input");
This will add two tags: tag1 and tag2 (note trailing ,).
Important: you should add data: [] into select2 init parameters.
Use an input type text, and assign the select2 to it. Like
<input type="text" id="makeTokens" />
and then in javascript
$("#makeTokens").select2({
placeholder: "Paste data",
tags: ["red", "green", "blue"],
tokenSeparators: [",", " "]
});
in the tags, you can assign any values that you want it to display as select options and use the tokenSeperators to seperate the text on commas or spaces etc.
Note: The resultant input value will be comma seperated tokens.
For some reason Donald's solution didn't work for me (maybe newer versions of select2 behaves differently). This is what worked for me:
$('body').on('paste', '.select2-input', function (e) {
var pasteData = (e.originalEvent || e).clipboardData.getData('text/plain') || '';
$(this).val(pasteData + ',');
e.preventDefault();
});
Since at the point the event was triggered the value of .select2-input was an empty string, I extractacted the pasted string from the event object. Apparently the default select2 for copying action was still triggering after this, so I had to add e.preventDefault(); to stop it from running and messing up the input.
just run this jQuery which takes the separatoes from options.tokenSeparators directly, and applies for all select2 instances in the page automatically:
$(document).on('paste', 'span.select2', function (e) {
e.preventDefault();
var select = $(e.target).closest('.select2').prev();
var clipboard = (e.originalEvent || e).clipboardData.getData('text/plain');
var createOption = function (value, selected) {
selected = typeof selected !== 'undefined' ? selected : true;
return $("<option></option>")
.attr("value", value)
.attr("selected", selected)
.text(value)[0]
};
$.each(
clipboard.split(new RegExp(select.data('select2').options.options.tokenSeparators.map(function (a) {
return (a).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}).join('|'))),
function (key, value) {
if (value && (!select.val() || (select.val() && select.val().indexOf('' + value) == -1))) {
select.append(createOption(value));
}
});
select.trigger('change');
});

how to get the child names when i select the parent in the tree view

I am using kendoUI tree view with check boxes implementation.
I am able to check all children's check boxes,when i select the parent checkbox.
now,I want to get all the children's text values when i select the parent check box.
I used template for check box operation in tree view
$("#ProjectUsersTreeView [type=checkbox]").live('change', function (e) { var chkbox = $(this);
var parent = chkbox.parent();
var pBox = $(parent).closest('.k-item').find(":checkbox");
if (this.checked || pBox.length>0) {
$(pBox).prop('checked',this.checked ? "checked": "")
}
Instead of using your code for checking children I do recommend using KendoUI configuration option checkChildren.
tree = $("#ProjectUsersTreeView").kendoTreeView({
checkboxes:{
checkChildren: true
},
...
}).data("kendoTreeView");
Then for getting all selected text use:
$("#ProjectUsersTreeView [type=checkbox]").live('change', function (e) {
var checked = $("input:checked", tree);
$.each(checked, function(idx, elem) {
console.log("text", tree.text(elem));
})
});
In checked I get all input elements from the tree that are actually checked and display its text on console by getting it using text method.
NOTE: Realize that I've defined tree as $("#ProjectUsersTreeView").data("kendoTreeView") and then use it in change handler.

Resources