Auto complete JQuery line separator - jquery-ui

i am already populating the autocomplete words and i wanted to have a line separator between the words for better identification in the auto complete.
Say the value in the drop down should be rendered as
Brijesh
-------
John
-------
Mike
Below is the snippet
$(document).ready(function () {
$("#studentName").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Webservice.asmx/GetStudentNames",
data: "{'prefixText':'" + request.term + "'}",
dataType: "json",
success: function (data) {
var regex = new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + request.term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi");
response($.map(data.d, function (item) {
return {
label: item.split('|')[0].replace(regex, "<Strong>$1</Strong>"),
val: item.split('|')[1]
}
}))
},
failure: function (response) {
ServiceFailed(result);
}
});
},
select: function (event, ui) {
txtStudent(ui.item.val, ui.item.label); //Student name and id used in this method
},
minLength: 2
});
});
Any leads would be appreciated.

How about simulating the separator with CSS. Something like:
autocomplete option {
padding-bottom: 4px;
border-bottom: 1px solid #ccc;
margin-bottom: 4px;
}

Use CSS
.ui-menu-item{
border-bottom: 1px dotted black;
}
fiddle here http://jsfiddle.net/JRM5Y/

Related

jquery select2 v4 store new options to data

I am using Select2 and I can create dynamic options using tags: true but when I select a previous option, the newly added option has disappeared.
How can I save it to data so it's always visible?
I've added a jsfiddle but it's not pretty but does demonstrate my problem
var data = [{
id: 0,
text: '<div style="font-size: 1.2em; color:green">enhancement</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: 'enchancement'
},
{
id: 1,
text: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>',
title: 'bug'
}];
$("#other").select2({
tags: true,
data: data,
escapeMarkup: function(markup) {
return markup;
},
createTag: function(params) {
var obj = {
id: 'new_' + params.term,
text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: params.term
};
return obj;
},
insertTag: function (data, tag) {
// Insert the tag at the end of the results
data.push(tag);
}
});
You need to trigger the select2:select function
Try this
$("#other").select2({
tags: true,
data: data,
escapeMarkup: function(markup) {
return markup;
},
createTag: function(params) {
var obj = {
id: 'new_' + params.term,
text: '<div style="font-size: 1.2em; color:blue">' + params.term + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>',
title: params.term,
isNew : true
};
return obj;
}
}).on('select2:select', function (e) {
if(e.params.data.isNew) {
data.push({id: e.params.data.id, text: '<div style="font-size: 1.2em; color:blue">' + e.params.data.text + '</div><div><b>Select2</b> supports custom themes using the theme option so you can style Select2 to match the rest of your application.</div>', title: e.params.data.text});
}
});

Jquery Autocomplete in mvc if user types text which is not in autocomplete list

Jquery Autocomplete UI in mvc .. If user enter some text which is not in list it should alert not in list ....
In View:-
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
if (data.length == 0) {
alert('Please select an item from the list');
document.getElementById('Loc').value = "";
document.getElementById('Loc').focus();
document.getElementById('Loc').style.border = "solid 1px red";
}
else
response($.map(data, function (item) {
document.getElementById('Location').style.border = "solid 1px black";
return { label: item.Name, value: item.Name, id: item.LocationId };
}));
}
})
},
select: function (event, ui) {
$("#locationID").val(ui.item.id);
}
});
in Controller:
public JsonResult AutoLoc(string term)
{
var result = (from r in db.S
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.id }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
Here suppose we enter 'a' then it will not alert any message . Though 'a' is not in list
when we enter any character which is not in autocomplete list it should alert and make that box as red.
Actually What is happening in 'data' we are getting values because in controller we are writing a query as contains or startwith 'a' so value is returned but as a individual 'a' is not in list that starts with or contains 'a'.
Try this:
$("#loc").autocomplete({
source: function(request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
if (found.length === 0) {
alert('Please select an item from the list');
$("#loc").val("");
$('#loc').focus();
$('#loc').css("border", "solid 1px red");
} else {
$('#loc').css("border", "none");
}
response(found);
}
});
},
select: function(event, ui) {
$("#locationID").val(ui.item.id);
}
});
In View:
$("#loc").autocomplete({
source: function (request, response) {
$.ajax({
url: "/a/AutoLoc",
type: "POST",
dataType: "json",
data: {term: request.term},
success: function(data) {
var found = $.map(data, function(item) {
return {label: item.Name, value: item.Name, id: item.LocationId};
});
}
});
},
change: function (event, ui) {
var referenceValue = $(this).val();
var matches = false;
$(".ui-autocomplete li").each(function () {
if ($(this).text() == referenceValue) {
matches = true;
return false;
}
});
if (!matches) {
alert('Please select an item from the list');
this.value = "";
this.focus();
this.style.border = "solid 1px red";
}
else {
document.getElementById("submitbutton").disabled = false;
this.style.border = "solid 1px black";
}
}
});
Now when we type 'a' it will alert and show the box border in red color......
This is what i wanted....

JQuery Autocomplete

I've got a problem with my jQuery autocomplete field. Its some kind of strange.
This is my autocomplete field and script. The response from my mvc function works fine. The Dropdownlist is visible entries. But when I'm trying to select an item the resultlist simply disappears. Does anyone have an idea?
<div class="ui-widget">
<input id="newPlayerName" type="text" name="newPlayerName" onkeyup="checkRegistration()" />
</div>
code:
<script type="text/javascript">
$(function () {
$('#newPlayerName').autocomplete({
source: function (request, response) {
$.ajax({
url: '/Trainer/Search',
data: {
searchTerm: request.term
},
dataType: 'json',
type: 'POST',
minLength: 1,
success: function (data) {
response(data);
}
});
},
select: function (event, ui) {
checkRegistration(ui.item.value);
},
focus: function (event, ui) {
event.preventDefault();
$("#newPlayerName").val(ui.item.label);
}
});
});
</script>
Ah ... this are the jquery scripts I'm using...
<script src="/Scripts/jquery-1.9.0.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.js" type="text/javascript"></script>
One thing that seems wrong with the code you have shown is the fact that you have included the jquery-ui script twice (the minified and standard versions). You should have only one:
<script src="/Scripts/jquery-1.9.0.js" type="text/javascript"></script>
<script src="/Scripts/jquery-ui-1.10.0.custom.min.js" type="text/javascript"></script>
$(function () {
var getData = function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/GetMultiProductList",
data: "{'term':'" + $("#txtAutoCompleteMulti").val() + "'}",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
if (item != null)
return { label: item.label, title: item.value }//value: item.label,
}))
},
error: function (result) {
alert("Error");
}
});
};
var selectItem = function (event, ui) { $("#txtAutoCompleteMulti").val(ui.item.value); return false; }
$("#txtAutoCompleteMulti").autocomplete({
source: getData,
select: selectItem,
_resizeMenu: function () {
this.menu.element.outerWidth(500);
},
search: function (event, ui) { },
minLength: 1,
change: function (event, ui) {
if (!ui.item) {
$('#txtAutoCompleteMulti').val("")
}
},
select: function (event, ui) {
$("#txtAutoCompleteMulti").prop('title', ui.item.title)
},
autoFocus: true,
delay: 500
});
});
.ui-autocomplete {
max-height: 300px;
overflow-y: auto;
overflow-x: hidden;
}
.ui-autocomplete-loading {
background: url('img/Progress_indicator.gif') no-repeat right center;
}
.seachbox {
border: 1px solid #ccc;
border-radius: 4px;
width: 250px;
padding: 6px 25px 6px 6px;
transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
}
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<div>
<table style="width: 100%;">
<tr>
<td style="width: 20%">Product Name :</td>
<td>
<input type="text" id="txtAutoCompleteMulti" placeholder="Seach Product" class="seachbox" />
</td>
</tr>
</table>
</div>
c# code using webmethod

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.

Jquery UI autocomplete event change

Hi I got a problem with change event.
By documntation there should be object ui.item
After an item was selected; ui.item refers to the selected item. Always triggered after the close event.
But when I try it ui.item is undefined :( I want unset s_town_id when input in autocomplete doesn't match with data from script.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
// ui.item is undefined :( where is the problem?
$("#s_town_id").val(ui.item.id);
}
});
});
I find out solution where I testing event.originalEvent.type if it is meneuselected or not and after fail I unset s_town_id. But any better solution is still wellcome.
<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id" />
$(function() {
$("#s_town").autocomplete({
source: function(request, response) {
$.ajax({
url: "/_system/_ajax/uiautocomplete.php",
dataType: "json",
data: {
name: "s_town",
term: request.term
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]",
value: item.whisper_name,
id: item.whisper_id,
zip_code: item.zip_code,
lup_state: item.lup_state,
stateid: item.stateid
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$("#s_town_id").val(ui.item.id);
},
change: function(event, ui)
{
try
{
if(event.originalEvent.type != "menuselected")
{
// Unset ID
$("#s_town_id").val("");
}
}
catch(err){
// unset ID
$("#s_town_id").val("");
}
}
});
});
if ui.item is not defined that means your json source is not well formed.
You have to send a json source like this:
[{"label":"Jean","value":1},{"label":"carl","value":2}]
You can add more key to the array but at least you have to set "label" and "value".
Check the json string.
Also I reckon you to use the last version of autocomplete 1.8.1 at the moment

Resources