javascript make select 2 use url set by outside source - javascript

I'm using select2 to pick out games from a database, however, the file I wish it to search from will change depending on what's selected from a dropdown.
How do I get it so select2 always uses the most up to date "picker_url"?
So if I select a certain option from a select box on a page, it changes the "picker_url" (an ajax file to do the search). The problem is, select2 only seems to use the original value.
Here's my current code:
var picker_url = "test1.php";
$(document).on('change', ".category_select", function(e)
{
var id = $(this).val();
if (id == 16)
{
picker_url = "test2.php";
}
});
$(".game_picker").select2({
selectOnClose: true,
width: '100%',
ajax: {
url: picker_url,
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
cache: true,
},
minimumInputLength: 2
});

Found the answer here: https://github.com/select2/select2/issues/1679#issuecomment-280080742
var someCondition
ajax: {
url: function() {
if (someCondition) {
return '/api/1/someFile.json'
} else {
return '/api/1/someOtherFile.json'
}
}
}

I suggest to use dynamic-urls, like the code below:
$('#mySelect2').select2({
ajax: {
url: function (params) {
return '/some/url/' + params.term;
}
}
});
Inside url function you can test other variables than params, like in the following snippet:
$('#category').select2({
placeholder: "Select category...",
width: '100%',
});
$('#category').on('select2:select', function(e) {
var data = e.params.data;
console.log("category", data);
categ = e.params.data.id;
});
var categ = "1";
$('#project').select2({
placeholder: "Select item...",
width: '100%',
ajax: {
type: "GET",
url: function(params) {
console.log("ajax func", params, categ);
var url = 'https://jsonplaceholder.typicode.com/comments?postId=' + categ
return url;
},
cache: true,
processResults: function(data) {
return {
results: $.map(data, function(obj) {
return {
id: obj.id,
text: obj.name
};
})
};
},
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<div class="group">
<select id="category">
<option value="1">cat 1</option>
<option value="2">cat 2</option>
</select>
</div>
<br>
<div class="group">
<select id="project">
<option value=""></option>
</select>
</div>

I would save off your default options and then recreate the select2 whenever you need to by extending your new URL into the default options:
var defaultOptions = {
selectOnClose: true,
width: '100%',
ajax: {
url: "test1.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj.id, text: obj.text };
})
};
},
cache: true,
minimumInputLength: 2
};
//Use default to create first time
$(".game_picker").select2(defaultOptions);
//On change, recreate
$(document).on('change', ".category_select", function(e)
{
var options = defaultOptions;
if ($(this).val() == 16)
{
//Create a new options object with the url updated
options = $.extend({}, defaultOptions, { url: 'test2.php' });
}
//Create a select2 with the desired options
$(".game_picker").select2(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

live search add a href to results

I have a live search in laravel 7
everything works good
but I cant add (href a tag) to result list
because result show in select option (select2 library) without (a) tag and cant be open in a new page for see result for this keyword
my blade:
<div class="fre-search-wrap">
<select class="livesearch form-control" name="Find Consultants"></select>
</div>
my scripst:
<script type="text/javascript">
$('.livesearch').select2({
placeholder: 'Select Consultants',
ajax: {
url: '/live_search/action',
dataType: 'json',
delay: 550,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
},
cache: true
}
});
the main source was this
https://www.positronx.io/laravel-autocomplete-search-with-select2-example/
Hello guy you can use this to add a tag:
$('.livesearch').select2({
placeholder: 'Select Consultants',
ajax: {
url: '/live_search/action',
dataType: 'json',
delay: 550,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: ""+item.title+"", // a tag
id: item.id
}
})
};
},
cache: true
}
});

Select2 : How to get other response from ajax?

sorry for my bad english. I just wanna ask about select2 ajax, i have problem with this, i don't know how to get other response from my API.
So this is the response from my API.
enter image description here
so i want to get zip_code value when select2 has on changed. but i don't know to get it.
this my code..
$(".myselect").select2(
{
theme: "bootstrap4",
placeholder: "Provinsi, Kota/Kab, Kecamatan, Kelurahan",
minimumInputLength: 3,
ajax: {
url: url, //changing by env
dataType: 'json',
type: "GET",
delay: 150,
data: function (params) {
return {
filter: params.term
};
},
processResults: function (data, params) {
var res = data.data.locations.map(function (item) {
return {
id: item.id,
text: item.name,
zip: item.zip_code
};
});
return {
results: res
};
},
templateResult: function(result) {
return result.text;
},
templateSelection: function(selection) {
return selection.text;
}
},
}).on('change.select2', function(e){
console.log($(this).val(e.text));
villText = $("#village option:last-child").text();
var villVal = $("#village option:last-child").val();
// console.log($("#village option:last-child").val())
// var villVal1 = $("#village option:last-child").val();
villKel = villText;
villKel = villKel.split(',')[2];
$("#village_kel").val(villKel);
var villx = $('#village_land');
var vill_land = $("#village_land option:last-child").text();
vill_land_kel = vill_land;
vill_land_kel = vill_land_kel.split(',')[2];
$("#villageland_kel").val(vill_land_kel);
$('input[name="domisili"]').click(function() {
if ($(this).attr("value") == "1") {
if(villx.empty()) {
villx.append($('<option></option>').attr('value', villVal).text(villText));
villx.prop('selectedIndex', 0);
}
else {
villx.append($('<option></option>').attr('value', "").text(""));
}
}
})
});
picture below is the result when i get the text of value from my API.
enter image description here

Set data of a Multiple Select2 element through javascript

I'm loading multiple values into a Select2 element through Javascript, ajax and jquery. While the data is loading properly and can be accessed once loaded, I'm unable to set stored data in the Select2 element.
Edit: I'm using Select2 v3.5.
My code:
HTML:
<input class="jsData" style="width: 100%" id="select2Data"></input>
Javascript:
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
contentType: 'application/json',
url: '<%=Url.Action("GetData","Controller")%>',
type: 'POST',
dataType: 'json',
data: function (term) {
return {
sSearchTerm: term
};
},
results: function (data) {
return {
results: $.map(JSON.parse(data), function (item) {
return {
text: item.term,
slug: item.slug,
id: item.Id
}
})
};
}
},
multiple: true
});
So, this creates a Select2 element where I can traverse to and from a database and load data depending on what I've typed. I can also access the data (entered by the user) using the following line:
$('.jsData').select2('val')
The above line returns an array, which I can store in the database. My current objective is to set the stored data back into the Select2 element. Any help in this matter would be most welcome.
Update: A relevant link for what I want to accomplish:
https://select2.github.io/examples.html#programmatic
I want the example of setting multiple elements in Select2. However, the difference would be in the fact that the example in the Select2 documentation brings data at the time of loading the page, while I will be making trips to fetch the data.
The Select2 v3.5.4 docs are a bit confusing around this. I think there's a typo in the docs that's misleading.
First, notice that when I retrieve the data from the remote source I'm returning it as an object in the format of {id: ##, name: NAME}.
The first step is to add the initSelection parameter and pass the function to retrieve the previously selected items.
The next step, where I believe there's a typo, is to define the formatSelection parameter (not the formatResult it states in the docs). This function defines how the previously selected result is displayed. In this case I'm merely showing the name property of the result.
The formatResult parameter defines how newly selected options are displayed. You'll notice formatResult and formatSelection are the same below. I could have reused a single function but felt this was better for demonstration.
$(document).ready(function() {
function formatResult(data) {
return data.name;
};
function formatSelection(data) {
return data.name;
}
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
results: function(data) {
return {
results: $.map(data, function(user) {
return {
name: user.name,
id: user.id
};
})
};
}
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
dataType: "json"
}).done(function(data) {
callback(data);
});
}
},
formatResult: formatResult,
formatSelection: formatSelection,
multiple: true
});
});
Here's the full working example:
$(document).ready(function() {
function formatResult(data) {
return data.name;
};
function formatSelection(data) {
return data.name;
}
$(".jsData").select2({
ajax: {
minimumInputLength: 4,
url: "https://jsonplaceholder.typicode.com/users",
type: "GET",
dataType: "json",
results: function(data) {
return {
results: $.map(data, function(user) {
return {
name: user.name,
id: user.id
};
})
};
}
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax("https://jsonplaceholder.typicode.com/users/" + id, {
dataType: "json"
}).done(function(data) {
callback(data);
});
}
},
formatResult: formatResult,
formatSelection: formatSelection,
multiple: true
});
});
.jsData {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css" rel="stylesheet"/>
<input class="jsData" style="width: 100%" id="select2Data" value="10"></input>

Select2 dropdown menu (ajax,initSelection) error "options.results is not a function"

I am using select2 plugin(ivaynberg.github.io/select2).
I am trying to display a dropdown(select).
Data getting via ajax, for this I create 2 servlets.
Dropdown menu url: '/testPr1/servlet1'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"},{"id":3,"text":"Genre3"},{"id":4,"text":"Genre4"}]
Init data url: '/testPr1/servlet2'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"}]
I create hidden element for select2 (and set init value)
Select film genre from list:
<input type="hidden" id="film_genre_cbox" style="width:600px" value="1,2" />
Then I get started with creating dropdown
var select_config2 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
},
initSelection: function (element, callback) {
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
};
$("#film_genre_cbox").select2(select_config2);
It works well, select exclude Genre1 and Genre2 as init value
But I want to see these two genres as selected elements in input, like this:
And then I tried to init select2 via ajax
var select_config1 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
// alert(id.toString());
if (id !== "") {
$.ajax({
url:'/testPr1/servlet2',
dataType: "json",
type: "GET",
quietMillis: 0,
}).done(function(data) {
alert(data.toString());
return callback(data);
});
} else {
callback([]);
}
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
};
$("#film_genre_cbox").select2(select_config1);
As result I get init selection as want
But when I start to dropdown I get no menu (Genre3,Genre4)
and error “Uncaught TypeError: options.results is not a function”.
Libs that I use
jquery-2.1.4.js
/select2_v3.5/select2.js
select2_v3.5/select2.css
Where is the mistake?

Load dropdown list based on another dropdown selected item

Load dropdown list based on another dropdown selected item
Here my js :
$("#Ownerstate").change(function () {
var procemessage = "<option value=`0`> Please wait...</option>";
$("#OwnerAgency").html(procemessage).show();
var url = "/Index/GetAgencyState/";
// Get state code
var Ownerstate = $("#Ownerstate :selected").val();
$.ajax({
url: url,
data: { statecode: Ownerstate },
cache: false,
type: "POST",
success: function (carData) {
if (carData.length > 1) {
$("#OwnerAgency").prop("disabled", false);
}
var select = $("#OwnerAgency");
select.html('');
$.each(carData, function (index, itemData) {
select.append($('<option/>', {
value: itemData.Value,
text: itemData.Text
}));
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Not getting load dropdownlist

Categories