How to display exact value from drop down? - jquery-select2

I have configured my select via select2 and things works quite well.
I have used templateResult with formatState approach to add the icon to my dropdown options.
$(".js-country-list").select2({
templateResult: formatState
});
that however does not change anything to selected value (see image below).
How can I make sure that selected value (in my case EUR) would be displayed exactly same as option: Euro (EUR)?
Thanks.

The templateSelection method described at https://select2.org/selections can be used to achieve this, it can be passed the same function used by templateResult.
$(".js-country-list").select2({
templateResult: formatState,
templateSelection: formatState
});
Example listing countries and their flags (not currencies) is incorporated below.
// Template function which adds CSS flag and displays country name
function flagTemplate(country){
return $("<span class='flag-icon flag-icon-" + country.id + " '></span><span class='flag-text'>" + country.text + "</span>");
}
// Generate correct URL based on entered search term
function generateUrl(params){
if(params.term){
return "https://restcountries.com/v3.1/name/" + params.term;
} else {
return "https://restcountries.com/v3.1/all";
}
}
// Initialise select2 using flagTemplate function for both result and selection
$('#countrySelect').select2({
// Set template for results and selection
templateResult: flagTemplate,
templateSelection: flagTemplate,
// Set placeholder text
placeholder: 'Select country...',
// Load country list from https://restcountries.com
ajax: {
url: generateUrl,
cache: 250,
dataType: "json",
processResults: function(data) {
return {
results: data
.map(x => ({id: x.cca2.toLowerCase(), text: x.name.common}))
.sort((a, b) => ('' + a.text).localeCompare(b.text))
};
}
}
});
#countrySelect {
width: 300px;
}
.flag-text {
margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<!-- Load flags using library https://github.com/lipis/flag-icons -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/4.1.5/css/flag-icons.min.css" rel="stylesheet"/>
<select id="countrySelect"><option></option></select>

Related

Redirect before selecting an item Select2

I'm using Select2 v4.0.3 and I populate the element using ajax.
$("#el").select2({
multiple: true
maximumSelectionSize: 1,
ajax: {
url: url,
data: function (params) {
return {
name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data.results, function(obj) {
return {id: obj.id, text: obj.name, key: obj.key};
}
})
};
}
}
});
I want to redirect the client before a result is selected. The problem is I need the key attribute from the clicked result. To understand better what I want to do, I paste here a snippet that works after the selection is made.
$("#el").on("select2:select", function(e) {
var selected = $(this).select2('data')[0];
location.href = base_url + '?key=' + selected.key;
});
You can use event.params.args.data.id to get the key attribute from the clicked result. So, your code would probably work like:
$("#el").on("select2:select", function(e) {
var selected = event.params.args.data.id;
location.href = base_url + '?key=' + selected;
});
I slightly modified the official Github repositories example to show my point.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
</head>
<body>
<select class="js-data-example-ajax" style="width: 100%">
<option value="3620194" selected="selected">select2/select2</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
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: $.map(data.items, function(ghrepo) {
return {
text: ghrepo.archive_url,
id: ghrepo.archive_url
}
})
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
minimumInputLength: 1
}).on('select2:selecting', function(event, params) {
event.preventDefault();
repoId = event.params.args.data.id;
console.log(repoId);
});
</script>
</body>
</html>

Autocomplete response

I'm trying to 'popup' jquery autocomplete result under a textbox using the popover components of bootstrap.
I render results of the autocomplete query in an hidden div (#wrapper) and I want on render completion to set the content of my popover and show it.
For this I've overloaded the _renderItem function which append my results' divs inside the hidden container (#wrapper).
I thought the response function is called when _renderItem calls are done but I'm missing something as response function is never called.
Any solution?
Thanks!
$("#bookSearch")
.autocomplete({
minLength: 0,
source: '/Autocomplete/Books',
focus: function (event, ui) {
$("#bookSearch").val(ui.item.label);
return false;
},
search: function(event, ui) {
$('#wrapper').empty();
},
response: function (event, ui) {
$('#bookSearch').popover('destroy');
$('#bookSearch').popover({
html: true,
placement: 'bottom',
content: $('#wrapper').html()
});
$('#bookSearch').popover('show');
}
})
.data("autocomplete")._renderItem = function (ul, item) {
$('<div class="media"></div>')
.data("item.autocomplete", item)
.append("<a class=\"pull-left\" href=\"#\"><img class=\"media-object\" src=\""
+ item.ImgUrl
+ "\"></a><div class=\"media-body\"><h6 class=\"media-heading\">"
+ item.Name
+ "</h6>"
+ item.Author + "</div>").appendTo('#wrapper');
};
I fixed the problem by adding to my css file a z-index style for the autocomplete.
.ui-autocomplete {
z-index: 10000;
}
Remember to set a higher value for the z-index if it is necessary. Just for the record I have something like this in the HTML file
<div class="ui-widget">
<label for="employee">Employee:</label>
<input id="employee" type="text" name="employee" />
</div>

remove <strong> from text box

I have implemented autocomplete using Jquery. I have also implemented highlighting the matching text. I am using <strong> tag in the high light function. When I go through the autocomplete dropdown one by one using keyboard arrows, the text where I am currently on, is displayed in the text box. When it displays, it displays with the <strong> tag. Any suggestions to remove the tag? I have given my code below.
<input type="text" id="institution-list"/>
<script type="text/javascript" language="javascript">
$(function () {
$("#institution-list").autocomplete({
source: function (request, response) {
$.ajax({
url: "/home/findinstitutions", type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: highlight(item.InstitutionName, request.term),
id: item.InstitutionId
};
}));
}
});
},
minLength: 3
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(item.label))
.appendTo(ul);
};
});
function highlight(s, t) {
var matcher = new RegExp("(" + $.ui.autocomplete.escapeRegex(t) + ")", "i");
return s.replace(matcher, "<strong>$1</strong>");
}
</script>
I think that the problem is that you're taking the label of your recently found data and render it as HTML, instead of plain text. Thus, instead of Berkeley, your autocomplete is showing <strong>Ber</strong>keley.
Try to parse it and remove any HTML tag before displaying it:
function sanitize(text){
var regex = /(<([^>]+)>)/ig;
return text.replace(regex, "");
}
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(sanitize(item.label)))
.appendTo(ul);
};
The regular expression was extracted from here: Remove HTML Tags in Javascript with Regex
Find below the solution I found for my problem
Existing code:
response($.map(data, function (item) {
return { label: highlight(item.InstitutionName, request.term),
id: item.InstitutionId
};
Solution:
response($.map(data, function (item) {
return { label: highlight(item.InstitutionName, request.term),
value: item.InstitutionName,
id: item.InstitutionId
};
The original code returned the label (which had embedded html tags) and no value. Since there was no value, the textbox used the label to display. Now, I explicitly assign the value of the text box with my text (without html tags) and that fixes my problem.
Here is the snapshot of how it appears now.

ASP.NET MVC Autocomplete position?

I use jquery-ui-auto-complete-with-multi-values. My textbox is downstream of page, But autocomplete-menu is opened above the page. I cant understand this bug. I used example that is on jquery site. Its is same examle.
I add jquery and css at the page.What could be the problem?
UPDATE
Script
<style>
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat;
}
</style>
<script>
$(function () {
var availableTags;
$.ajax({
url: '#Url.Action("GetTags", "Question")',
type: 'GET',
cache: false,
beforeSend: function () {
// Show your spinner
},
complete: function () {
// Hide your spinner
},
success: function (result) {
availableTags = result;
}
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});
</script>
Controller
[HttpGet]
public JsonResult GetTags()
{
var data = entity.Tags.Select(x => new { label = x.TagName, value = x.TagName });
return Json(data, JsonRequestBehavior.AllowGet);
}
Razor
<div class="demo">
<div class="ui-widget">
#Html.TextBoxFor(x => x.Title, new { #class = "my_text_box", id = "tags" })
</div>
</div>
<!-- End demo -->
<div class="demo-description">
<p>
Usage: Enter at least two characters to get bird name suggestions. Select a value
to continue adding more names.
</p>
<p>
This is an example showing how to use the source-option along with some events to
enable autocompleting multiple values into a single field.
</p>
</div>
Css
.ui-autocomplete {
position: absolute;
cursor: default;
}
ul, menu, dir {
display: block;
list-style-type: disc;
-webkit-margin-before: 1em;
-webkit-margin-after: 1em;
-webkit-margin-start: 0px;
-webkit-margin-end: 0px;
-webkit-padding-start: 40px;
}
Thanks.
I found the problem. Its about CurCss in jquery-ui version that I have. In older version of jquery-ui has not this method. I got script refrence from google-apis. Problem is fixed now.
Thanks.

How to return jquery autocomplete result to the separate div?

I've found here that to overwrite one of the autocomplete events. But can somebody please provide me with example how to do the same?
The appendTo option does indeed work as expected, and if you inspect at the DOM, the <ul> results element will be attached to the element. However, due to absolute positioning generated by jQueryUI, the list still appears directly under the <input>.
That said, you can override the internal _renderItem to directly append results to a completely different element, for example:
HTML
<input id="autocomplete"/>
<div class="test">Output goes here:<br/><ul></ul></div>
JavaScript
$('input').autocomplete({
search: function(event, ui) {
$('.test ul').empty();
},
source: ["something", "something-else"]
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li/>')
.data('item.autocomplete', item)
.append(item.value)
.appendTo($('.test ul'));
};
I have also created a demo to demonstrate this. Please note that the latest jQuery library has not had jQueryUI tested against it fully, so I am using the previous version which allows me to select to include jQueryUI directly with the jsFiddle options.
<div class="test">Output goes here:<br/></div>
<script>
$("input#autocomplete").autocomplete({
source: ["something", "something-else"],
appendTo: ".text",
position: { my: "left top", at: "left bottom", of: ".test" }
// other options here
});
</script>
I needed more control over where to put the data, so this is how I went about it:
$("#input").autocomplete({
minLength: 3,
source: [
"ActionScript",
"AppleScript",
"Asp"
],
response: function(event, ui) {
console.log(ui.content);
// put the content somewhere
},
open: function(event, ui) {
// close the widget
$(this).autocomplete('close');
}
});
hle's answer worked awesome for me and gives you more flexibility! Here is my test code that was modified by his answer:
$("#autocomplete").autocomplete({
minLength: 3,
source: ["something", "something-else"],
response: function(event, ui)
{
console.log(ui.content);
// put the content somewhere
},
open: function(event, ui)
{
// close the widget
$(this).autocomplete('close');
}
});
Although this question is pretty old but i got a pretty easy solution. No hack, nothing just in jQuery way:
Instead of autocomplete response function, just add response data in div on success
$(document).ready(function () {
$("#book-code-search").autocomplete({
minLength: 2,
delay: 500,
source: function (request, response) {
$.ajax( {
url: "server side path that returns json data",
data: { searchText: request.term, param2 : $("#type").val()},
type: "POST",
dataType: "json",
success: function( data ) {
$("#data-success").html(data.returnedData); //returnedData is json data return from server side response
/* response($.map(data, function (item) {
return {
label: item.FullDesc,
value: item.FullDesc
}
})) */
}
});
}
});
});
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div id='data-success' style='color: green;'></div>
<input type='text' placeholder='Enter Book Code' id='book-code-search' />
<input type='hidden' id='type' value='book'>

Resources