Set selected value on select2 without loosing ajax - javascript

I have this select2 code in my html (mvc with razor) page:
$('#QuickSearchState').select2({
minimumInputLength: 3,
width: 'resolve',
ajax: {
url: '#Url.Action("QuickSearchState", "DataCenter")',
contentType: 'application/json',
dataType: 'json',
type: 'POST',
traditional: true,
quietMillis: 400,
data: function(term, page) {
var data = {
term: term
};
return data;
},
results: function(data, page) {
return { results: data };
}
},
initSelection: function(element, callback) {
var data = { id: element.val(), text: element.val() };
callback(data);
},
formatResult: function(format) {
return format.label;
},
formatSelection: function(format) {
//this is a knockout view model
vmNewAddress.IdState(format.id);
vmNewAddress.StateName(format.stateName);
return format.label;
},
dropdownCssClass: "bigdrop",
escapeMarkup: function(m) { return m; }
});
But i have another select in my code that can set a state in this select, but i dont know how to set this value to that select.
In my html i have this:
<select class="width-xl" data-bind="options: vm.GivenLocationsForConnection, optionsText: 'DisplayFormat', value: SelectedLocation"></select> -> first select that can fill the second state search select with a state
#Html.Hidden("query", null, new { #id = "QuickSearchState", #class = "width-xl", placeholder = "Ej. Montevideo" }) -> second select, this is a search for states and selects a single state

I am not sure if this is what you want but if you only want to select a value in the select you can just do below
$("#QuickSearchState").select2("val", "<YOUR VALUE>");

Related

Bug: Select2 Ajax Multiselect Checkbox Does't Delete (Deselect) When You Double Click(Toggle) On Select

This is Select2 library
Checkbox normally works after double clicks. It carries out the Add and Delete operation.
But when I use the ajax multiselect checkbox, it can add but I cannot delete it through select.
When I want to delete, I can only delete it by pressing x on the top.
This is my code : https://codepen.io/tolga-kurtulu/pen/KKaOVXp?editors=1011
enter image description here
HTML
<select class="select2" style="width: 100%;" multiple="multiple"></select>
Javascript
$(document).ready(function() {
$("select.select2").select2({
closeOnSelect: false,
placeholder: "Placeholderr",
// allowHtml: true,
allowClear: true,
tags: true,
// debug: true,
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
data: (params) => {
return {
q: params.term,
}
},
processResults: (data, params) => {
const results = data.items.map(item => {
return {
id: item.id,
text: item.full_name || item.name,
};
});
return {
results: results,
}
},
},
});
})

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

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?

Autocomplete - change lookup/serviceurl based on dropdown selection

I have a dropdown with multiple options to select. When I select value1 (company), autocomplete should use the service call. When I select value2, lookup should be used.
How can I implement this?
$('#qckSearchKeyword').autocomplete({
serviceUrl: function() {
var option = $('#qck-unspsc').val();
if (option == "country") {
// when country selected through drop down i should use lookup rather then service call
serviceloc = "getCountries";
localStorage.option = "country";
}
if (option == "industry") {
serviceloc = "getSicCode";
localStorage.option = "sicCode";
}
return serviceloc;
},
onSelect: function(suggestion) {
localStorage.tmpSelectedTxt = $.trim($('#qckSearchKeyword').val());
$('#selectFromSuggestions').val("true");
$('#qckSearchKeyword').focus();
},
paramName: "searchTerm",
delimiter: ",",
minChars: 3,
transformResult: function(response) {
// alert(response);
return {
suggestions: $.map($.parseJSON(response), function(item) {
return {
value: item.suggesCode,
data: item.suggesString
};
})
};
}
});
Split up the options for the different autocomplete calls.
Use a data-type on the options you select.
Switch the data-type and extend the proper options
Init autocomplete with proper options
I simply copy/pasted some configuration I've done in the past for this functionality:
...
ajaxOptionsFlight: {
url: '/api/autocomplete/airport/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsHotel: {
url: '/api/locations/hotel/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsCitytrip: {
url: 'http://budapest.onlinetravel.ch/destfinder',
dataType: 'jsonp',
data: {
vendors: 'merger',
client: 'conbe',
filter: 'IATA',
format: 'json',
language: 'en'
}
},
ajaxOptionsCar: {
url: '/api/locations/car/',
dataType: 'json'
},
ajaxOptionsSubstitute: {
url: 'http://gd.geobytes.com/AutoCompleteCity',
dataType: 'jsonp'
},
autocompleteOptions: {
autoFocus: true,
minLength: 1
},
....
After that I make sure I can switch on data-type and hook it on the source parameter of the autocomplete options:
autocompleteOptions = $.extend({}, autocompleteOptions, {
source: type === 'citytrip' ? function (request, response) {
ajaxOptions = $.extend(true, {}, ajaxOptionsCitytrip, {
data: {
name: $.trim(request.term),
language: cookieLanguage
},
success: function (d) {
response($.map(d.Destinations, function (item) {
return {
label: item.name + ', ' + item.country,
value: item.name,
code: item.olt_id
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'flight' ? function (request, response) {
ajaxOptions = $.extend({}, ajaxOptionsFlight, {
url: ajaxOptionsFlight.url + $.trim(request.term),
success: function (d) {
response($.map($(d).find('airport'), function (item) {
return {
label: $(item).children("displayname").text(),
value: $(item).children("displayname").text(),
code: $(item).children("code").text()
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'hotel' ? function (request, response) {
// and so on ...
}
});
Not the most elegant way of writing, I admit. But it's basically a simple mapping between data-type and configuration options to provide for autocomplete.
In the end I only call:
input.autocomplete(autocompleteOptions);
And we're done. Hope that makes sense.

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