how to dynamic function use ajax jquery in select2 - javascript

so I use this code to make everything that has the $(".select2") element will process ajax according to the rest of the data sent via html
$(".select2").each(function () {
let element = $(this);
element.select2({
theme: "bootstrap",
placeholder: element.data("placeholder"),
ajax: {
url: element.data("url"),
dataType: 'json',
delay: 100,
cache: true,
data: function (params) { return { q: params.term } },
processResults: function (data) {
return {
results: $.map(data.results, function (item) {
return {
text: item.bank_name, /***** this *******/
id: item.id /***** this *******/
}
})
};
}
},
});
})
I've added element.data ("placeholder") and element.data ("url") in jquery, while how to send it with this html code
<select id="bank_id" name="bank_id"
class="fetch_bank form-control select2"
data-placeholder="Choose Bank"
data-url="/api/bank/fetch">
</select>
sending it ajax will return the following results
{
code: 200
error: false
message: "loaded!"
results: [
{id: 1, bank_name: "AMERICAN EXPRESS BANK LTD"},
{id: 2, bank_name: "ANGLOMAS INTERNASIONAL BANK"},
....
]
}
I have 3 records that return json, to display to select2, the column is as below
Bank(id, bank_name)
School(id, school_name)
Status(id, status)
but the problem is, how do i make 'processResults' dynamic? which I have marked with a comment / ***** this ******* /
While the 3 data has different keys, how do I make the select2 function dynamic?
thanks, I hope someone answers my question :)

Related

Select2: Creating tags with ajax

I am using the select2 library.
My select2 element can search the database for each tag via the ajax and that works fine.
My issue is, I want the user to also be able to create a new tag. Looking at their documentation I should use the createTag option; however, this fires as soon as I click into the element and on each key press.
Can anyone offer any guidance on how I can achieve my goal?
here is my code thus far
I am using ajax top search for tags but I would also like to create new tags to the database. I have tried doing this via createTag but this seems to be firing as soon as I click in the HTML element and on each key press.
Here is my code:
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
cache: true,
},
createTag: function(params) {
alert('tag created') // This is were I would put my ajax POST.
}
});
After reading the documentation again, I can see I should have been using the events https://select2.org/programmatic-control/events
I used the createTag option to assign newTag: true to newly created tags and used the select2:selected event which checked if a new tag had been selected and, if it was, sent an ajax request to the server to create that tag.
$('.tags').select2({
tags: true,
placeholder: "These tags will apply to all lines",
minimumInputLength: 3,
tokenSeparators: [','],
ajax: {
url: '/api/tags/find',
dataType: 'json',
data: function (params) {
return {
q: $.trim(params.term)
};
},
processResults: function (data) {
return {
results: data
}
},
// cache: true,
},
createTag: function(params) {
let term = $.trim(params.term);
if (term.length < 3)
{
return null
}
return {
id: term,
text: term,
newTag: true,
}
},
});
$('.tags').on('select2:select', function (e) {
let tag = e.params.data;
if (tag.newTag === true)
{
axios.post('/api/newtag', {
name: tag.text,
type: 'default',
})
}
});

select2 programmatically without knowing results in advance

I am trying to write a test for a Javascript select2 control and I would like to automatically select the first item. Since it's using ajax I do not know what the first item is. All the examples I have seen create <option> however they assume knowledge of the value. How can I select the first item without knowledge? (Note this example only runs the ajax command after 3 items are entered).
var $selector = $("#foo");
$selector.show().select2({
allowClear: true,
placeholder: "--------",
minimumInputLength: 3,
ajax: {
url: "...",
type: 'GET',
dataType: 'json',
delay: 250,
data: function(term, page) {
return {
number__icontains: term
};
},
results: function(data) {
return {
results: $.map(data.objects, function(option) {
return {
'id': option.id,
'text': option.desc
};
})
};
},
cache: false
},
initSelection: function(element, callback) {
...
}
});

Unable to select result from select2 dropdown

I have the following javascript/jQuery that pulls in data from via AJAX. That works fine however I can cannot seem to be able to select an option from the dropdown? Can anyone explain what I have done wrong..
This is something to do with the id..
$(".js-data-example-ajax").select2({
ajax: {
url: "/admin/generator/teams",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
id: function(data){ return data._id; },
});
First you should make sure processResults function returns an array of objects with id and text properties like this:
{ id: '1', text: 'Option 1' }
Then once the options are loaded, you can set the value by calling:
$(".js-data-example-ajax").val('1').trigger('change');

select2JS Ajax Option Value

I'm developing a form with select2JS.
In my first step I use a simple Select2
$(this).select2();
But I want to change it for an Ajax version.
$(this).select2({
multiple:multival,
ajax:
{
url: '/api/v2/vocabulary/'+vocabulary+'/words/list',
headers: {'X-AUTHORIZATION-TOKEN': token},
dataType: 'json',
type: "POST",
quietMillis: 100,
data: function (params) { // Lors d'une recherche
return {
pattern: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.words,
pagination: {
more: (params.page * 15) < data.total
}
};
},
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
cache: true
},
escapeMarkup: function (markup) {return markup; }, // let our custom formatter work
minimumInputLength: 0,
templateResult: function formatRepo (repo)
{
return repo.name;
},
templateSelection: function formatRepoSelection (repo)
{
return repo.name;
}
});
In the first version, my Ajax return the name of the Option ( When I send the form). In the Ajax version, the script create a new Option inside the select ( But not visible ) and when I send the form its an Id who is sent. Because in the Value of the new Option, its the Id and not the name.
I use Select2 4.0.1 and I find in the 3162' Line :
if (data.id) {
option.value = data.id;
}
I tried to change data.id by data.name, but it was not effective.
Do you have an idea?

Forcing select2 ajax call

I have 2 select2 and when one of them changes the other one loads it's content using the built in select2 ajax function, the problem is that in the case only one element comes from the server I want it to be loaded by default, but for what I have seen the ajax call is only executed when opening the select2 in question. Here is the code I run when the first selec2 is changed in order to change the second's data:
$select1.on('change', function () {
initializeLocationsSelect2($select2, $select1.val(), $template, omId);
});
function initializeLocationsSelect2(tag, s1Value, template, id) {
tag.val("");
tag.select2({
placeholder: "Please Select One",
minimumInputLength: 0,
multiple: true,
tokenSeparators: [","],
tags: false,
ajax: {
url: tag.data('url'),
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return {
id: id,
value: s1Value
};
},
results: function (data, page) {
return {
results: data
};
}
},
formatSelection: function (item) {
return $.format(template.html(), item.text);
},
formatResult: function (item) {
return $.format(template.html(), item.text);
},
escapeMarkup: function (m) { return m; }
});
}
just in case it is relevant, the second select2 is attached to a <hidden> tag

Categories

Resources