For my autocomplete I sort my results into 3 sections "title", "company", "tag".
I would like to have a headline for each section.
In practise I want to add <div class='ui-optionHeader'>Headline</div> before the li elements, I think.
I cant figure it out, either the headline is above every single element or it doesnt work at all.
I made an visual explanation - This is what I aim for:
Here is my code:
$(document).ready(function() {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
searchOption : $("#search_option").val()
},
success: function(data) {
response(data);
}
});
},
select: function(event, ui) {
$('#search_text').val(ui.item.value);
},
minLength: 1,
open : function(){
// $(".ui-autocomplete:visible").css({top:"+=13"});
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
if(item.option==="title") {
return $( "<li>" )
.append( "<div><i class='fas fa-tags'></i> " + item.label + "<br> title </div>" )
.appendTo( ul );
}
else if(item.option==="company"){
return $( "<li>" )
.append( "<div><i class='fas fa-building'></i> " + item.label + "<br> company </div>" )
.appendTo( ul );
}
else if(item.option==="tags"){
return $( "<li>" )
.append( "<div><i class='fas fa-utensils'></i> " + item.value + "<br> tags </div>" )
.appendTo( ul );
}
};
});
What it currently looks like:
Thanks in advance.
An Example:
$(function() {
$.widget("custom.catcomplete", $.ui.autocomplete, {
_create: function() {
this._super();
this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)");
},
_renderMenu: function(ul, items) {
var that = this,
currentCategory = "";
$.each(items, function(index, item) {
var li;
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
li = that._renderItemData(ul, item);
if (item.category) {
li.attr("aria-label", item.category + " : " + item.label);
}
});
}
});
var data = [{
label: "anders",
category: ""
},
{
label: "andreas",
category: ""
},
{
label: "antal",
category: ""
},
{
label: "annhhx10",
category: "Products"
},
{
label: "annk K12",
category: "Products"
},
{
label: "annttop C13",
category: "Products"
},
{
label: "anders andersson",
category: "People"
},
{
label: "andreas andersson",
category: "People"
},
{
label: "andreas johnson",
category: "People"
}
];
$("#search_text").catcomplete({
delay: 0,
source: data
});
});
.ui-autocomplete-category {
background: #009F84;
color: #fff;
font-weight: bold;
padding: .2em .4em;
margin: 0;
line-height: 1.5;
}
form #search {
border: 1px solid #000;
line-height: 2em;
margin: 0;
padding-left: .5em;
width: 75%;
}
form button {
background: #009F84;
border: 0;
color: #fff;
font-weight: bold;
padding: .65em 2em;
margin-left: 0;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form>
<input id="search_text"> <button type="submit">Find</button>
</form>
Related
This is how I insert new data to kendo grid, however i want my added row have a custom class, so I can style my new added row with different background color. How can I achieve this ? I searching all the doc can't find any related
var dataSource = $('#grid').data('kendoGrid').dataSource;
dataSource.insert(0, {
"name":"ABC",
"age": 99
});
In order to add a new class to each newly row you can use .addClass(). But, every time you move to the next/prev page or add other rows you need to add again the class....
In order to achieve that you can save in a global array a list of all newly added row uuid and on dataBound event reapply the class.
Fiddle here
var newUUID = [];
$("#grid").kendoGrid({
navigatable: true,
filterable: true,
pageable: {
pageSize: 5,
alwaysVisible: false,
pageSizes: [5, 10, 20, 100]
},
dataBound: function(e) {
$.each(newUUID, function(idx, ele) {
if ($(ele).length != 0) {
$(ele).addClass('newRow');
}
})
}
});
$('#btn').on('click', function(e) {
var dataSource = $('#grid').data('kendoGrid').dataSource;
var x = dataSource.insert(0, {
"name":"ABC",
"age": 99
});
newUUID.push("[data-uid='" + x.uid + "']");
$("[data-uid='" + x.uid + "']").addClass('newRow');
})
You can look-up the newly added row by its UID and add the class to the row.
I explored the solution on this blog: "Simple Row Coloring in a KendoUI Grid"
const sampleData = getSampleData();
$(document).ready(() => {
$("#example-grid-wrapper").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns
});
setTimeout(insertNewRecordAfterOneSecond, 1000);
});
function insertNewRecordAfterOneSecond() {
// Insert data
let dataGrid = $('#example-grid-wrapper').data('kendoGrid');
dataGrid.dataSource.insert(0, { id: 1, name: "Sam", location: "B", color: "blue", status: 0 });
// Re-scan table and lookup newly added row.
dataGrid = $('#example-grid-wrapper').data('kendoGrid');
let dataView = dataGrid.dataSource.view();
for (let i = 0; i < dataView.length; i++) {
if (dataView[i].id === 1) {
dataGrid.table.find("tr[data-uid='" + dataView[i].uid + "']").addClass("highlighted-row");
}
}
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid-wrapper">
<div id="example-grid"></div>
</div>
Alternative
As suggested by gaetanoM.
const sampleData = getSampleData();
var insertedUidList = [];
$(document).ready(() => {
$("#example-grid").kendoGrid({
dataSource: {
data: sampleData.data,
schema: {
model: {
fields: sampleData.fields
}
}
},
columns: sampleData.columns,
// Suggested by gaetanoM
dataBound: function(e) {
$.each(insertedUidList, function(idx, uid) {
// Re-apply class to existing rows.
$(`tr[data-uid="${uid}"]`).addClass('highlighted-row');
});
}
});
// Insert two rows, one second apart.
insertRowsWithDelay([
{ id: 0, name: "Joseph", location: "A", color: "yellow", status: 1 },
{ id: 1, name: "Sam", location: "B", color: "blue", status: 0 },
], 1000)
});
function insertRowsWithDelay(data, delayBetween) {
if (data == null || data.length === 0) return;
setTimeout(() => {
insertNewRecord(data.pop());
insertRowsWithDelay(data, delayBetween);
}, 1000);
}
function insertNewRecord(record) {
record = $('#example-grid').data('kendoGrid').dataSource.insert(0, record);
insertedUidList.push(record.uid);
$(`[data-uid="${record.uid}"]`).addClass('highlighted-row');
}
function getSampleData() {
return {
data : [
{ id: 2, name: "Grant", location: "A", color: "green", status: 1 },
{ id: 3, name: "Vaughan", location: "B", color: "red", status: 0 },
{ id: 4, name: "David", location: "A", color: "orange", status: 1 }
],
fields : {
id: { type: "number" },
name: { type: "string" },
location: { type: "string" },
color: { type: "string" }
},
columns : [
{ field: "id", title: "ID", width: "10%" },
{ field: "name", title: "Name", width: "30%" },
{ field: "location", title: "Location", width: "30%" },
{ field: "color", title: "Color", width: "20%" },
{ field: "status", title: "Status", width: "10%" }
]
};
}
.highlighted-row {
background: #FF0; /* Higlight row yellow */
}
.highlighted-row.k-alt {
background: #DD0; /* Higlight row yellow */
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://kendo.cdn.telerik.com/2019.2.619/js/kendo.all.min.js"></script>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2019.2.619/styles/kendo.blueopal.min.css" />
<div id="example-grid"></div>
You can try to create a databound function for the grid and then try this inside the function
function onDataBound(e) {
var dataSource = $("#GridName").data("kendoGrid").dataSource;
var data = dataSource.data();
$.each(data, function (index, rowItem) {
if (data.length > 0) {
var rows = e.sender.tbody.children();
var row = $(rows[index]);
if (data[index].name == "ABC" ) {
row.addClass("NameColor");
}
}
});
}
<style>
.NameColor {
background-color: black;
}
</style>
Like this you can try..
I am getting error after taking a react render from something like this
return (
React.createElement('form', {
onSubmit: this.onSubmit,
className: 'ContactForm',
noValidate: true
},
React.createElement('input', {
type: 'text',
className: errors.name && 'ContactForm-error',
placeholder: 'Name',
onInput: this.onNameInput,
value: this.props.value.name,
}),
React.createElement('button', {
type: 'submit'
}, "Add Contact")
)
);
to something like this
function create_input_element(type, fieldname){
var capital_fieldname = capitalize(fieldname);
return React.createElement('input', {
type: type,
className: errors[fieldname] && 'ContactForm-error',
placeholder: capitalize(capital_fieldname),
onInput: this['on' + capital_fieldname + 'Input'],
value: this.props.value[fieldname],
autoFocus: true,
})
}
create_input_element('text', 'name')
The issue is at this.props.value[fieldname], and even this.props.value.name will break with the same error.
The exact code is
<head>
<style>
body {
font-family: Tahoma, sans-serif;
margin: 0;
}
.ContactView-title {
font-size: 24px;
padding: 0 24px;
}
.ContactView-list {
list-style: none;
margin: 0;
padding: 0;
border-top: 1px solid #f0f0f0;
}
.ContactItem {
margin: 0;
padding: 8px 24px;
border-bottom: 1px solid #f0f0f0;
}
.ContactItem-email {
font-size: 16px;
font-weight: bold;
margin: 0;
}
.ContactItem-name {
font-size: 14px;
margin-top: 4px;
font-style: italic;
color: #888;
}
.ContactItem-description {
font-size: 14px;
margin-top: 4px;
}
.ContactForm {
padding: 8px 24px;
}
.ContactForm>input {
display: block;
width: 240px;
padding: 4px 8px;
margin-bottom: 8px;
border-radius: 3px;
border: 1px solid #888;
font-size: 14px;
}
.ContactForm>input.ContactForm-error {
border-color: #b30e2f;
}
</style>
<meta name="description" content="Ridiculously Simple Forms with Raw React - Exercise Two">
<script src="https://cdn.rawgit.com/zloirock/core-js/master/client/shim.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<div id="react-app"></div>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react.js"></script>
<script src="https://cdn.jsdelivr.net/react/0.14.0-rc1/react-dom.js"></script>
<script>
/*
* Components
*/
function capitalize(str){
return str.charAt(0).toUpperCase() + str.substring(1)
}
var ContactForm = React.createClass({
propTypes: {
value: React.PropTypes.object.isRequired,
onChange: React.PropTypes.func.isRequired,
onSubmit: React.PropTypes.func.isRequired,
},
onEmailInput: function(e) {
this.props.onChange(Object.assign({}, this.props.value, {
email: e.target.value
}));
},
onNameInput: function(e) {
this.props.onChange(Object.assign({}, this.props.value, {
name: e.target.value
}));
},
onSubmit: function(e) {
e.preventDefault();
this.props.onSubmit();
},
render: function() {
var errors = this.props.value.errors || {};
function create_input_element(type, fieldname){
var capital_fieldname = capitalize(fieldname);
return React.createElement('input', {
type: type,
className: errors[fieldname] && 'ContactForm-error',
placeholder: capitalize(capital_fieldname),
onInput: this['on' + capital_fieldname + 'Input'],
value: this.props.value[fieldname],
autoFocus: true,
})
}
return (
React.createElement('form', {
onSubmit: this.onSubmit,
className: 'ContactForm',
noValidate: true
},
create_input_element('email', 'email'),
create_input_element('text', 'name'),
React.createElement('button', {
type: 'submit'
}, "Add Contact")
)
);
},
});
var ContactItem = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
email: React.PropTypes.string.isRequired,
},
render: function() {
return (
React.createElement('li', {
className: 'ContactItem'
},
React.createElement('h2', {
className: 'ContactItem-email'
}, this.props.email),
React.createElement('span', {
className: 'ContactItem-name'
}, this.props.name)
)
);
},
});
var ContactView = React.createClass({
propTypes: {
contacts: React.PropTypes.array.isRequired,
newContact: React.PropTypes.object.isRequired,
onNewContactChange: React.PropTypes.func.isRequired,
onNewContactSubmit: React.PropTypes.func.isRequired,
},
render: function() {
var contactItemElements = this.props.contacts
.map(function(contact) {
return React.createElement(ContactItem, contact);
});
return (
React.createElement('div', {
className: 'ContactView'
},
React.createElement('h1', {
className: 'ContactView-title'
}, "Contacts"),
React.createElement('ul', {
className: 'ContactView-list'
}, contactItemElements),
React.createElement(ContactForm, {
value: this.props.newContact,
onChange: this.props.onNewContactChange,
onSubmit: this.props.onNewContactSubmit,
})
)
);
},
});
/*
* Constants
*/
var CONTACT_TEMPLATE = {
name: "",
email: "",
description: "",
errors: null
};
/*
* Model
*/
// The app's complete current state
var state = {};
// Make the given changes to the state and perform any required housekeeping
function setState(changes) {
Object.assign(state, changes);
ReactDOM.render(
React.createElement(ContactView, Object.assign({}, state, {
onNewContactChange: updateNewContact,
onNewContactSubmit: submitNewContact,
})),
document.getElementById('react-app')
);
}
// Set initial data
setState({
contacts: [{
key: 1,
name: "James K Nelson - Front End Unicorn",
email: "james#jamesknelson.com"
}, {
key: 2,
name: "Jim",
email: "jim#example.com"
}, ],
newContact: Object.assign({}, CONTACT_TEMPLATE),
});
/*
* Actions
*/
function updateNewContact(contact) {
setState({
newContact: contact
});
}
function submitNewContact() {
var contact = Object.assign({}, state.newContact, {
key: state.contacts.length + 1,
errors: {}
});
if (!/.+#.+\..+/.test(contact.email)) {
contact.errors.email = ["Please enter your new contact's email"];
}
if (!contact.name) {
contact.errors.name = ["Please enter your new contact's name"];
}
setState(
Object.keys(contact.errors).length === 0 ?
{
newContact: Object.assign({}, CONTACT_TEMPLATE),
contacts: state.contacts.slice(0).concat(contact),
} :
{
newContact: contact
}
);
}
</script>
</body>
Why can't I generate React.createElement() things in a function? Thank you
It's a scope problem. You can learn here how the variable this works .
To solve your problem, you can use call to explicit pass this variable of the scope where the function is being invoked.
The code would look like like this: create_input_element.call(this, 'email', 'email')
Javascript returns object object error while executing this code.As i am new to javascript,i am not able to identify the specific issue.Also the name of the user story is not properly aligned wiht the Userstory id.Looking for help.Thanks in advance.
<!DOCTYPE html>
<html>
<head>
<title>UserStoryWithPredecessors</title>
<script type="text/javascript" src="https://rally1.rallydev.com/apps/2.0p5/sdk.js"></script>
<script type="text/javascript">
Rally.onReady(function() {
Ext.define('CustomApp', {
extend: 'Rally.app.App',
componentCls: 'app',
launch: function() {
Ext.create('Rally.data.WsapiDataStore', {
model: 'UserStory',
fetch:
['Iteration','FormattedID','Name','Predecessors','PredecessorID','Project','ScheduleState'],
filters: [
{
property: 'Iteration.Name',
operator: '=',
value: 'RT4 Iteration #4'
}
],
autoLoad: true,
listeners: {
load: this._onDataLoaded,
scope: this
}
});
},
_onDataLoaded: function(store, data) {
var records = [];
Ext.Array.each(data, function(record) {
//Perform custom actions with the data here
//Calculations, etc.
var myPredecessors = record.get('Predecessors');
var predecessorData = "";
var predecessorCreationDate = "";
var predecessorState = "";
var predecessorProject = "";
var predecessorID = "";
var predecessorName = "";
// Loop through and process Predecessor data
for (var i=0; i<myPredecessors.length; i++) {
thisPredecessor = myPredecessors[i];
thisPredecessorFormattedID = thisPredecessor["FormattedID"];
thisPredecessorName = thisPredecessor["Name"];
thisPredecessorScheduleState=thisPredecessor["ScheduleState"];
thisPredecessorProject= thisPredecessor["Project"];
// Post-pend updated data to value for array
// predecessorData += thisPredecessorFormattedID + ": " +
thisPredecessorName + "<br>"
predecessorID += thisPredecessorFormattedID + "<br>";
predecessorName += thisPredecessorName + "<br>";
predecessorState += thisPredecessorScheduleState + "<br>";
predecessorProject += thisPredecessorProject + "<br>";
}
records.push({
FormattedID: record.get('FormattedID'),
Name: record.get('Name'),
Iteration:
(record.get('Iteration')&&record.get('Iteration')._refObjectName) || '',
PredecessorID : predecessorID,
PredecessorName : predecessorName,
PredecessorState: predecessorState,
PredecessorProject: predecessorProject,
});
});
this.add({
xtype: 'rallygrid',
store: Ext.create('Rally.data.custom.Store', {
data: records,
pageSize: 20
}),
columnCfgs: [
{
text: 'Iteration', dataIndex: 'Iteration', width: '100px'
},
{
text: 'FormattedID', dataIndex: 'FormattedID', width: '100px'
},
{
text: 'Name', dataIndex: 'Name', width: '400px'
},
{
text: 'PredecessorID', dataIndex: 'PredecessorID', width: '100px'
},
{
text: 'PredecessorName', dataIndex: 'PredecessorName', width:
'200px'
},
{
text: 'Project', dataIndex: 'PredecessorProject', width: '200px'
},
{
text: 'State', dataIndex: 'PredecessorState', width: '400px'
}
//,
//{
// text: 'Predecessor Creation Date(s)', dataIndex:
'PredecessorCreationDate', width: '200px'
// }
]
});
}
});
Rally.launchApp('CustomApp', {
name: 'UserStoryWithPredecessors'
});
});
</script>
<style type="text/css">
.app {
/* Add app styles here */
}
</style>
</head>
<body></body>
</html>
i have found an answer the question my self.I did small modification in the code and it works.
thisPredecessorProject= thisPredecessor["Project"]._refObjectName;
I need to Print this sheet in to a Report.Looking for yours assistance.Thanks in advance.
On click on #add I am calling add_table_row() to add new row in table
<tr class="item" id="item1">
<td><input type="text" name="billProductList[0].product.name"
id="billProductList_0__product_name" class="name></td>
..............
</tr>
Each row in similar to above one only the numbers are incremented by one.
For first .name jquery autocomplete is working properly but for dynamically added row it is not working
function add_table_row() {
var t = $('.table .item:last').attr('id');
var prs = t.slice(4);
var num1 = parseInt(prs) + 1;
var dataString = 'rowId=' + num1;
$.ajax({
type: "POST",
url: "getNewBillRow",
data: dataString,
dataType: "html",
success: function(data) {
$(".table .item:last").after(data);
}
});
}
$(document).on('click', '#add', function(event) {
event.preventDefault();
add_table_row();
});
$(".name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
How to make it to work for all .name .
This is because when you bind autocomplete() to .name, the other controls (dynamic controls) doesn't exist in the DOM. So you need to rebind the function after adding the control to the DOM.
You can do something like this:
function BindAutoComplete() {
$(".name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
Then in your ajax call :
function add_table_row() {
var t = $('.table .item:last').attr('id');
var prs = t.slice(4);
var num1 = parseInt(prs) + 1;
var dataString = 'rowId=' + num1;
$.ajax({
type: "POST",
url: "getNewBillRow",
data: dataString,
dataType: "html",
success: function(data) {
$(".table .item:last").after(data);
BindAutoComplete();
}
});
}
After you add the new row, you need to initialize autocomplete on the newly added .name field.
success: function(data) {
$(".table .item:last").after(data);
$(".table .item:last .name").autocomplete({
source: function(request, response) {
$.ajax({
url: "ProductByName",
dataType: "json",
data: {
name: request.term,
maxRows: 12
},
success: function(data) {
response($.map(data.productList, function(item) {
console.log(item);
return {
label: item.name,
value: item.name,
id: item.id,
desc: item.desc,
}
}));
},
error: function(data) {
console.log(typeof data);
}
});
},
minLength: 1,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
var pid = $(this).parents('.item').attr('id');
//alert(ui.item.id + " " + ui.item.desc);
$("#" + pid + " .id").val(ui.item.id);
$("#" + pid + " .description").val(ui.item.desc);
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
}
The problem I am facing here is http://jqueryui.com/autocomplete/#categories I am unable to figure out how to make "No result found" appear in the drop down list of auto complete menu search. Can someone share there insight on how this can be achieved?
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Autocomplete - Categories</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
</style>
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var data = [
{ label: "anders", category: "" },
{ label: "andreas", category: "" },
{ label: "antal", category: "" },
{ label: "annhhx10", category: "Products" },
{ label: "annk K12", category: "Products" },
{ label: "annttop C13", category: "Products" },
{ label: "anders andersson", category: "People" },
{ label: "andreas andersson", category: "People" },
{ label: "andreas johnson", category: "People" }
];
$( "#search" ).catcomplete({
delay: 0,
source: data
});
});
</script>
</head>
<body>
<label for="search">Search: </label>
<input id="search" />
</body>
</html>
$( "#search" ).catcomplete({
delay: 0,
source: data
});
Replace To:
$( "#search" ).catcomplete({
delay: 0,
source: function(request, response) {
var result = data.slice(0);
result = $.ui.autocomplete.filter(result, request.term);
if(! result.length) {
result.push({
label: 'No Result Found',
category: "",
isPlaceholder: true
});
}
response(result);
}
});
See Example