how to pass $(this) of select2 inside ajax parameters - javascript

I need to pass $(this) of select2 inside ajax to get data-url like like code below it, $(this).data("url") not working.
$(".select-ajax").select2({
allowClear: $(this).data('allowclear') ? $(this).data('allowclear') : false,
ajax: {
url: $(this).data("url"),
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
// 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
return {
results: data
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatRepo,
templateSelection: formatRepoSelection
});

The easiest way to deal with this and similar situations is to set a constant to refer to.
const selectAjax = $(".select-ajax");
selectAjax.select2({
allowClear: selectAjax.data('allowclear') ? selectAjax.data('allowclear') : false,
ajax: {
url: selectAjax.data("url"),
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
// 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
return {
results: data
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatRepo,
templateSelection: formatRepoSelection
});

You need to set this as a variable.
var that = $(this);
that.select2({
...
//other code
url: $(that).attr("data-url")
//other code
});

Related

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

Select2 Loading remote data but params.page undefined

Below is my code copied from https://select2.github.io/examples.html to load remote data via Select2 in my Asp.net MVC 4 project, which displayed in a Bootstap Modal dialog, however, it always shows "params.page" is undefined, it do worked if I put a "page:1" there. What's the problem?
$("#ReportToEmployeeName").select2({
placeholder: "Select Report To",
ajax: {
url: 'myurl ',
dataType: 'json',
delay: 250,
data: function (params) {
console.log(params);
return {
term: params.term, // search term
page: params.page //Undefined error here
//page: 1 // do worked, but then pagination will not work
};
},
processResults: function(data, params) {
params.page = params.page || 1;
return {
results: data.Results,
pagination: {
more: (params.page * pageSize) < data.Total
}
};
},
cache: true
},
//escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
allowClear: true,
//templateResult: formatRepo, // omitted for brevity, see the source of this page
//templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

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');

Select2 - start ajax search on enter

I have a Select2 input which I use to search (remote data).
Currently, it works like this:
when user types 1 one more characters we trigger search automatically
Now, the fun part:
I need to add following behaviour:
when user focus on in this input and just hits Enter button, I need to trigger search with one character '*' BUT without actually writing that character in the input.
It should just send search request with character * but input should stay empty.
Is that even possible without messing Select2 code?
My code:
$("#account").select2({
language: "en",
ajax: {
url: window.urls.ajax_account_search,
dataType: 'json',
delay: 500,
data: function(params){
console.log(params);
return {
query: params.term,
page: params.page
}
},
processResults: function(data, params){
return {
results: data.items
}
},
cache: true
},
escapeMarkup: function(m) { return m; },
templateResult: formatSearchResult,
templateSelection: formatSearchSelection,
minimumInputLength: 1
});
Instead of triggering the search on enter (with * being sent), you can just send * when there is no search term present. This also means dropping the minimumInputLength requirement, but that seems to line up with what you are looking for.
$("#account").select2({
language: "en",
ajax: {
url: window.urls.ajax_account_search,
dataType: 'json',
delay: 500,
data: function(params){
return {
query: params.term || '*', // send * if there is no term
page: params.page
}
},
processResults: function(data, params){
return {
results: data.items
}
},
cache: true
},
escapeMarkup: function(m) { return m; },
templateResult: formatSearchResult,
templateSelection: formatSearchSelection
});

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?

Categories

Resources