Using Select2 4.0 in my forms' select elements, those intented to be filled dynamically in Ajax mode are not working in IE9. It displays an empty select with no placeholder.
The ones in classic mode (pre-filled select lists) are displaying and working (select2 search..) correctly.
Using the older version 3.5.2 in other pages, the problem doesn't occur...!
Is this a known issue? Fixable one?
Thx
Here's the JS:
$(".select2Ajax").not(".select2-container").each(function(){
var min = $(this).data('min'); // 3
var configs = {
"width":"100%",
language: $locale, // 'fr'
ajax: {
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data, page) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: min
};
$(this).select2(configs);
})//.each
The HTML:
<select id="contrat_kam" name="contrat[kam]" class="select2Ajax form-control" data-min="3" data-ajax--url="/My/Ajax/Source/url-returning-json-formatted-list/from-search-term">
<option value="">Here is my intitial placeholder</option>
</select>
And an example of what's returned form the server when typing into the select2 field, in a normal client (Chrome):
[{"id":"75484567","text":"Bestnameever Ronald"},{"id":"12344568","text":"Nameofdude C\u00e9dric"},{"id":"01202795","text":"SecondDudesName John"},{"id":"00709297","text":"Doe John"}]
Thank you
Ok I solved my problem, but it wasn't a JS/IE problem.
I am working under Symfony 2. The problem appeared after the form submit. Having a validation error, Symfony displays the form page again with the errors on the fields.
I was using Select2 in AJAX mode because the choices list was way too heavy to handle, nearly causing the browser to crash with more than 7000 options to display..
So I created the select (sf2 entity choice list) with an empty array for choices list.
BUT
If you try to save your form with the new value, which was NOT in the (empty) original choice list, SF doesn't validate it, and throws a validation error.
SO
you have to add a form PRE_SUBMIT event listener, to add the select with your selected value in it, to your formType.
Which is complete other subject :)
The problem was that the new select that I defined in the form event listener did'nt have the correct parameters (class, data attributes..), preventing the select2 to work.
My bad!
So the subject would rather find his place in a Symfony 2 thread..
Related
I am using a Select2 dropdown in my HTML form. The HTML for that looks like
<select required id="item-search" name="items[]" multiple="multiple">
</select>
The JavaScript to activate the Select2 looks like
<script type="text/javascript">
$(document).ready(() => {
$('#item-search').select2({
placeholder: "sample",
maximumSelectionLength: 10,
ajax: {
url: "http://127.0.0.1:5000/validate",
dataType: "json",
data: function (params) {
var query = {
search: params.term,
email: "{{email}}"
}
return query;
},
},
minimumInputLength: 1,
});
}
</script>
But on my Flask backend, the request body for this form contains a key for the Select2 items[], but the value is simply a string rather than a comma separated list of IDs.
'items[]': '1'
I had 3 different items selected with IDs 1, 2, and 3. It is only returning the first.
I have tried:
Using a class instead of an ID to identify the Select2
Using a name of items[][]
A different name such as tags[]
Removing the required attribute
Different selection combinations
Temporarily using hard-coded <option> instead of those returned by the server
I have also read through the Select2 docs, and this was one of the most basic examples. I also read the following stack overflow posts:
select2 multi-value only sending one value in POST
Multiple select2 returning only a single selection on form submit
I've run out of ideas as to what might be going wrong here. I'm considering resorting to writing the selections to the DOM as inputs by binding to a Select2 event, and including that with the form. But I'd much prefer to get this working the right way and figure out this puzzle.
Found the solution
The frontend was totally fine. Flask was automatically casting the form data to key value pairs of strings, which when applied to an array just stringifies the first element in the array as the value to that key. The solution to get the full array uncasted in Flask is to call request.form.getlist('items[]'). I found this in the Werkzeug documentation here
I'm developing an ASP.NET MVC Application using Selectize.js in my search (action=GET) form. One of the inputs uses Selectize as follows:
$("#selectize").each(function () {
$(this).selectize({
plugins: ['remove_button'],
valueField: 'Acronym',
labelField: 'Name',
searchField: ['Acronym', 'Name'],
create: false,
persist: false,
preload: true,
initUrl: "/Attorneys/GetAllJson/",
initData: true,
load: function (query, callback) {
$.ajax({
url: "/Attorneys/GetAllJson/",
type: 'GET',
error: function () {
callback();
},
success: function (res) {
callback(res);
}
});
}
});
});
Everything if ok when the form is empty. The option shows the acronym and the name of the attorney perfectly in the Selectize input. Submitting the form, the input sends the values correctly separated by commas, as expected.
When I perform a search, the form is filled correctly with the values I've previously selected in the previous screen, but the attorney's names don't appear with the respective acronyms.
Listing the available options, all the other attorneys are showed correctly. The selected attorneys appear only as the acronyms.
I tried this (I don't use data-data: I use the value from input) and the solutions from this (didn't work).
Is there a way to reload these selected options with the proper remote values?
I'm using Select2 version 4.0.0 and trying to load a remote JSON from a PHP script that returns the already formated data that I need. The problem is that the forces of the darkness are making something, because I just can't send the request, there is no error, but there is no request sent, it just stays so quiet as a devil that I'm almost crying!
I'm using LiveScript and Jade as alternatives to JavaScript and HTML, but I'll translate'em here.
First, my markup defines the selectable field:
<select id="satan-hates-me"></select>
Then, I'm able to make it look like a selectable element:
$("#satan-hates-me").select2({
placeholder: "Hail",
minimumInputLength: 1,
ajax: { // Here that bad things happen, I mean, don't happen
url: "http://localhost/os/backend/TestServiceOrder.php?req=getEquipments",
dataType: "json",
type: "GET",
quietMillis: 50,
data: function(term) { return { term: term } },
results: function(data) { return data; }
}
});
I'm performing this wrapped in a load function, after page loading, it looks like a selectable, but sends no requests, and the script returns me exactly the required format, as example:
[{id: 1, text: "Sadness"}, {id: 2, text: "Depression"}]
And here goes. I can design compilers but I can't in the world make a plugin work with Ajax! Can somebody help me, please?
Finally resolved the issue.
<input> is not supported in select2 v4
.You have to use <select> element instead
In my case, it was a general select2-call of .select2-Elements in the footer of all my templates:
$('.select2').select2();
Event though my select for the Ajax-Request didn't have that class at all (I called it via an id), I had to change the above to
$('select.select2').select2({theme: 'classic'});
I guess select2() creates several elements with the class .select2, so that might interfere
I have a fairly simple requirement set, but cannot for the life of me figure out how to achieve it with Select2...
I would like to have an input on the page
Which the user can type into to trigger an AJAX call
Which also displays a pre-loaded list of options that the user can click on instead of typing to trigger the AJAX.
If you close (blur) the input and then reopen it again then the previously loaded AJAX responses should still be displayed (instead of the options being blank and you having to start typing to load them again).
I can do #1 and #2 (or #1 and #3 of course!), but I cannot get all three requirements in one input field. I've not found any way to do #4.
Effectively, to achieve #3, I guess I'm looking for a way to inject my shortlist into what are normally the ajax-returned options and use something like #4 to make sure these are not cleared when the field is opened.
Is there a way to initialise the (normally Ajax loaded) options for a Select2 field? I've tried passing in data but it doesn't work, I tried using initSelection until I realised that wasn't relevant, I've tried all sorts of things, but to no avail...
Hopefully this is possible and I've just missed an option somewhere!
P.S. I've read several threads on Stack with similar titles to this but none of them seem to answer this question. If I've missed the vital one just let me know!
I think you can do this if you use Select2's query option, rather than the ajax option. That way you can make the ajax request if any characters have been typed, but show the default list if no characters have been typed.
If your default options are defined like this:
var DEFAULT_OPTIONS = [
{ id: 'def1', text: 'Default Choice 1' },
{ id: 'def2', text: 'Default Choice 2' },
{ id: 'def3', text: 'Default Choice 3' }
];
You could do the following:
var lastOptions = DEFAULT_OPTIONS;
$('#select').select2({
minimumInputLength: 0,
query: function(options) {
if (options.term) {
$.ajax({
type: 'post', // Or 'get' if appropriate
url: 'your_ajax_url',
dataType: 'json',
data: {
term: options.term // Change name to what is expected
},
success: function(data) {
lastOptions = data;
options.callback({ results: data });
}
});
} else {
options.callback({ results: lastOptions });
}
}
});
jsfiddle
This is my first time using Twitter's typeahead.js. I've got parts of it working, but what's not working is when I type ahead, the drop down list under the input text box is supposed to fill with values, but instead for me it says "undefined".
Here's my client-side code:
$(document).ready(function () {
$('input.typeahead-devs').typeahead({
name: 'movies',
remote: {
url: 'http://localhost:61182/api/SixFilm/GetMovies?term=%QUERY',
dataType: 'json',
}
});
});
The URL in the code above works and returns valid JSON. Here's my UI and my Firebug output:
I have a feeling I'm getting "undefined" because my "typeahead" doesn't know what to put for the values in the drop down list. Is there a particular variable I'm missing in my .typeahead call? How would I construct my typeahead correctly so that I get values in my drop down list?
I solved my problem. I needed valueKey. valueKey in my example is "Name", which is what I want to populate the drop down list:
$(document).ready(function () {
$('input.typeahead-devs').typeahead({
name: 'movies',
remote: {
url: 'http://localhost:61182/api/SixFilm/GetMovies?term=%QUERY',
dataType: 'json',
}
valueKey: "Name",
});
});