Select 2 jQuery Searching - javascript

I am using this jQuery plugin http://ivaynberg.github.io/select2/ with a data source linked to my employe database. The "Term" being used is last name however the jSON response is the full name.
When the result is Smith, John and you type smith it shows fine but when you try to include the first name to narrow it down even more, it stops the search as the comma is not part of the term.
$("[name=manager]").select2({
multiple: false,
minimumInputLength: 3,
placeHolder: 'Manager Last name',
allowClear: true,
ajax: {
url: "jsonUser.php",
dataType: 'json',
data: function (term) {
return {
term: term, // search term
};
},
results: function (data) { // parse the results into the format expected by Select2.
return {results: data};
}
},
});
The jSON response looks like this:
[{"id":"12345","text":"Smith, John"}
Anyone know of a way to make is so the full response is searchable and not just the term?

Related

How to include a label in jQuery Select2?

I've set up a Select2 instance that queries my database and renders the results via AJAX on an input that the user has access to.
Everything is working but as this is a location selection input for a user and there are districts and municipalities with same names, for example, I want to add a label for each result to identify them either as "District", "Municipality", "Parish", etc. but I'm unable to do so, I've been unable to find any support on this matter on the Internet and the extension itself doesn't seem to be able to do this,
Select2 AJAX Function
$("#location-property-alert-location").select2({
placeholder: "Type the name of the location",
minimumInputLength: 2,
ajax: {
url: '/ajax/search-locations-by-query',
dataType: 'json',
type: "GET",
data: function data(params) {
return {
query: params.term // search term
};
},
processResults: function processResults(response) {
// return{
// results: response.name
// };
response = response.map(function (item) {
// console.log(item);
return {
id: JSON.stringify(item), // json_encode the data so we can pass this through the ID
code: JSON.stringify(item),
test: "hello",
text: item.location_name
};
});
console.log(response);
return {
results: response
};
},
cache: true
}
});
I know Select2 can take additional data parameters such as the code and test parameters I added above but I don't know how exactly I can use these to create elements within the results with each item's category, for example, as portrayed in the screenshot below.
Each item's category is being stringified so I can pass this data through the form's submission either way but I need to identify each item's category on the frontend for the user to be able to differentiate locations,
Anyone has any idea on how to do this?
Cheers
Note: I don't want Select2's label appearance which basically groups options per category.
You can use templateSelection which will format your selection appearance and then change the result according to your json data.
Below is the demo for how this works with random json data.
function formatResult(item) {
//checks if the id present or not
if (!item.id) {
return item.text;
}
//return the format options..
var element = $(`<span>${item.text}<span class="text_small">${item.username}</span></span>'`)
return element;
};
$("#location-property-alert-location").select2({
placeholder: "Type the name of the location",
minimumInputLength: 2,
ajax: {
url: 'https://jsonplaceholder.typicode.com/users', //this is just for demo...
dataType: 'json',
type: "GET",
data: function data(params) {
return {
query: params.term // search term
};
},
processResults: function processResults(response) {
response = response.map(function(item) {
return {
id: JSON.stringify(item.id),
text: item.name,
username: item.username //pass here extra param
};
});
return {
results: response
};
},
cache: true
},
templateResult: formatResult //your selection format
});
.text_small {
font-size: 10px;
color: grey;
margin-left: 10px;
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css">
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select id="location-property-alert-location" style="width:300px"></select>

jquery-ui autocomplete: show a list of pair ID-Name in the dropdown list but with ID hidden

I have an asp.net app which consists of a master page and a web form with a master page.
Web form contains a label and a textbox:
Enter department name: <input type="text" value="" id="lstDepartments" />
I have implemented the jQuery autocomplete using jquery-ui. When user starts typing in the textbox I call a web api method using jquery ajax which search for department names containing the substring typed and finally it returns a JSON with the results with below structure:
[
{
DeptID: "83838383",
Name: "DepartmentName_1"
},
{
DeptID: "63343434",
Name: "DepartmentName_2"
},
{
DeptID: "3444555",
Name: "DepartmentName_3"
}
]
jQuery Ajax call is:
function ConfigureAutocomplete() {
$("#lstDepartments").autocomplete({
source: function (request, response) {
$.ajax({
url: "https://www.mycompany.es/MyWebapis/Departments/search/" + request.term,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return { value: item}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 1 // minimum 1 character to start searching
});
}
The call to the web api method is going ok, it returns a JSON with above structure stated.
What I am trying to do now without success is below:
Now I am trying to show those DeptID-Name pairs contained in the JSON in the textbox, but I want to hide DeptID on the textbox, I mean, I only want to show Names. So for example if I type "department" in the textbox below should be displayed in it as a dropdown list:
DepartmentName_1
DepartmentName_2
DepartmentName_3
Then, once user select one of them from that dropdown list, I need to call another web api using another jquery ajax call. When user selects one item of the dropdown list I want to get its corresponding ID and pass it to the web api method as a parameter in order to get detailed information of that department using its ID.
How can I do that things?
Check the documentation for jquery ui autocomplete. There is an event for selected item that you can use: https://api.jqueryui.com/autocomplete/#event-select. The "ui" parameter contains the value of the selected option, which you can use to pass it to the ajax call.

Select2 go to href link

I'm using Select2 js library but I can't not put the links into the select options.
Here is my json structure
[{id: 1, title: "Foo", slug: "foo"}]
And my select2 script
$(".search-box").select2({
placeholder: "Enter...",
ajax: {
url: window.location.href + '/search',
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
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: $.map(data, function (item) {
return {
text: item.title,
id: item.id
}
})
};
},
cache: true
},
minimumInputLength: 2,
maximumSelectionLength: 6
});
What I expect is when i type and click the title of SELECT OPTION i want the browser go to the post's address (link)
So any help plzzz
You cannot put window.location.href in the URL. Instead, use proper page URL path.
window.location.href is mainly use for page redirection.

How to use select2 with remote data if the data items don't provide the "id" and "text" fieldnames?

I have a select2 dropdown, which is configured for using with remote data. However, my remote datasource provides the search results in a format which seems to be not compatible with select2. The remote data is for example like this:
...
items: [ { value: 1, displayText: "First" }, { value: 2, displayText: "Second" } ]
...
but select2 seems to expect the "id" and "text" fields instead. I've checked all options, and tried to play with formatSelection, formatResult callbacks, but had no success until now, I always get javascript errors about "item.text" being undefined.
I cannot provide a jsFiddle because the web API is not public unfortunately.
Is there a way to configure select2 for using a custom "id" and "text" field? Or what else could be a good workaround for this scenario?
Ok, I figured it out almost immediately after I posted my question. Probably this is not the most efficient way to do this, so I'm still happy if someone has a better answer.
I managed to do a conversion in the results callback in the ajax options.
$("#mySelect").select2({
minimumInputLength: 3,
ajax: {
url: '/',
params: {
type: 'POST',
dataType: 'json',
},
quietMillis: 200,
data: function(term, page) { // page is the one-based page number tracked by Select2
return {
search: term,
pageSize: 10,
pageIndex: page-1,
};
},
results: function(data, page) {
var more = (page * 10) < data.Total; // whether or not there are more results available
return { results: $.map(data.Results, function(e, i) {
return { id: e.value, text: e.displayText, data: e };
}), more: more };
}
}

Select2 Plugin not eliminating options based on input

I am trying to work with the Select2 plugin in conjunction with the CodeIgniter framework. After a lot of effort, I managed to get it to work with AJAX data. However, now it has a weird problem. Even after typing in the entire name, the plugin does not eliminate the irrelevant options that do not match with the search term.
The below screenshot depicts this.
http://i.imgur.com/MfLcuf6.jpg?1
The Firebug console looks like this:
http://i.imgur.com/Qvko6mX.jpg
Below is my the Javascript code as well as the code for my controller
Javascript:
$("#mentor-typeahead").select2({
width: "100%",
placeholder: "Enter a mentor name",
maximumSelectionSize: 5,
minimumInputLength: 2,
multiple: true,
ajax: {
url: 'get_mentor_multi_list',
quietMillis: 500,
cache: true,
dataType: 'json',
results: function (data) {
return { results: data };
}
}
});
Controller
function get_mentor_multi_list($query = null)
{
$answer = array(array('id'=>1, 'text'=>'Inigo Montoya'),
array('id'=>2, 'text'=>'Zoey Deschanel'),
array('id'=>3, 'text'=>'Harry Potter'),
array('id'=>4, 'text'=>'Nicole Scherzinger'),
array('id'=>5, 'text'=>'Xerxes Mistry'),
array('id'=>6, 'text'=>'Tom Marvollo Riddle'),
array('id'=>7, 'text'=>'Light Yagami'),
array('id'=>8, 'text'=>'Vic Mackey'),
array('id'=>9, 'text'=>'Clark Kent'));
echo json_encode($answer);
}
I am utterly confused as to what could be causing the problem. I also tried the solution listed here link but to no avail. Any help would be appreciated.
Changed the AJAX call parameters on request but the output remains the same...
$("#mentor-typeahead").select2({
width: "100%",
placeholder: "Enter a mentor name",
maximumSelectionSize: 5,
minimumInputLength: 2,
multiple: true,
ajax: {
url: 'get_mentor_multi_list',
quietMillis: 200,
dataType: 'json',
data: function (term, page) {
return {
q: term,
page_limit: 10
};
},
results: function (data, page) {
return data;
}
}
You're missing a data function in the ajax part. See Loading Remote Data and Infinite Scroll with Remote Data in the documentation.
ajax: {
url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
dataType: 'jsonp',
quietMillis: 100,
data: function (term, page) { // page is the one-based page number tracked by Select2
return {
q: term, //search term
page_limit: 10, // page size
page: page, // page number
apikey: "ju6z9mjyajq2djue3gbvv26t" // please do not use so this example keeps working
};
},
results: function (data, page) {
var more = (page * 10) < data.total; // whether or not there are more results available
// notice we return the value of more so Select2 knows if more results can be loaded
return {results: data.movies, more: more};
}
}
You're not using the ajax function correctly. It's doing exactly what it's supposed to do and that is to display all of the data returned from your get_mentor_multi_list() function.
In order to do this correctly, your ajax call needs to include a data attribute that includes parameters to be sent to your get_mentor_multi_list() function. get_mentor_multi_list() will then return only the results that your user is looking for.
If the data in get_mentor_multi_list() is static (i.e. not read from any database), you should consider adding it to the data attribute like in the Loading Array Data example here.
Finally, I was able to resolve the problem by myself. The problem lay in the fact that I was using CodeIgniter. Hence whatever variables that were supposed to be passed through the data attribute of the AJAX call weren't actually being passed to the controller.
I resolved this by changing the Javascript code to the following:
JavaScript
$('#mentor-typeahead').select2({
width: "100%",
placeholder: "Enter a mentor name",
maximumSelectionSize: 5,
minimumInputLength: 2,
multiple: true,
ajax: {
url: 'get_mentor_multi_list',
quietMillis: 200,
dataType: 'json',
data: function (term, page) {
return {
searchq: term // set the search term by the user as 'searchq' for convenient access
};
},
results: function (data, page) {
return {
results: data
};
}
}
});
And the controller code to look something like the following:
function get_mentor_multi_list()
{
// model code
$query = trim($_GET['searchq']); // get the search term typed by the user and trim whitespace
if(!empty($query))
{
// retrieve data from database
}
else
{
$answer = array('id' => 0, 'text' => 'No results found');
}
echo json_encode($answer);
}

Categories