jqueryUi autocomplete - custom data and display - javascript

My full code is here: http://jsfiddle.net/HfNk9/13/
I am looking to this example jqueryUi autocomplete - custom data and display.
Let's suppose the object projects is different and it looks like this:
project = [
{
name: 'bar',
value: 'foo',
imgage: 'img.png'
}
]
If I set source = project the autocomplete refers to project.value and not project.name.
How should I change this behaviour?
var autocomplete = function(element, data) {
var fixtures = [
{
avatar: "http://www.placekitten.com/20/20",
name: 'aaaaaaaaa',
value: 'bbbbbbbbb'}
];
element.autocomplete({
minLength: 3,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(fixtures, function(value) {
return matcher.test(value.name);
}));
},
create: function() {
console.log(fixtures)
element.val(fixtures.name);
},
focus: function(event, ui) {
element.val(ui.item.name);
return false;
},
select: function(event, ui) {
element.val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a><img src="' + item.avatar + '" />' + item.name + '<br></a>')
.appendTo(ul);
};
};
autocomplete($('#auto'));
My full code: http://jsfiddle.net/HfNk9/13/

You need to filter on a different property than the autocomplete widget searches on by default (as you've noticed it's name or value when using a source array with objects).
You can use a function instead of an array as the source and perform your own filtering that way:
element.autocomplete({
minLength: 3,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(fixtures, function(value) {
return matcher.test(value.name);
}));
},
create: function() {
console.log(fixtures)
element.val(fixtures.name);
},
focus: function(event, ui) {
element.val(ui.item.name);
return false;
},
select: function(event, ui) {
element.val(ui.item.name);
return false;
}
}).data('autocomplete')._renderItem = function(ul, item) {
return $('<li></li>')
.data('item.autocomplete', item)
.append('<a><img src="' + item.avatar + '" />' + item.name + '<br></a>')
.appendTo(ul);
};
Example: http://jsfiddle.net/QzJzW/

You should use the select property:
$("...").autocomplete({
source: ...,
select: function( event, ui ) { //when an item is selected
//use the ui.item object
alert(ui.item.name)
return false;
}
});

The answer is in the source code to the page you've linked to. If you want to use the value of name instead of value then you would do something like this:
$( "#input" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#input" ).val( ui.item.value );
return false;
},
select: function( event, ui ) {
$( "#input" ).val( ui.item.value );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.name + "</a>" )
.appendTo( ul );
};

Related

Knockout: autocomplete on combobox binding not clearing the observable

I have an autocomplete combobox using both knockout and jquery ui libraries.
When you type something in that is not in the autocomplete list, the combobox gets blank and that is exactly what I want it to do, but it does not update my selectedOption value too (I would like to set it to null when the combobox is left blank)
I have tried adding a subscribe event to the selectedOption but knockout does not fire it in this case. I also tried with the valueAllowUnset property but it did not work either.
Thank you very much for your help!
Here is my snippet (it looks a bit ugly because I did not add CSS but it shows the problem):
function viewModel() {
var self = this;
self.myOptions = ko.observableArray([{
Name: "First option",
Id: 1
},
{
Name: "Second option",
Id: 2
},
{
Name: "Third option",
Id: 3
}
]);
self.selectedOption = ko.observable(3);
}
var myViewModel = new viewModel();
ko.applyBindings(myViewModel);
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<html>
<body>
<p> Combobox: </p>
<select id="myCombo" data-bind="options: myOptions, optionsText: 'Name', optionsValue: 'Id', value: selectedOption, valueAllowUnset: true, combo: selectedOption"></select>
<p> Option selected Id: </p>
<texarea data-bind="text: selectedOption()"> </texarea>
</body>
</html>
<script>
// ko-combo.js
(function() {
//combobox
ko.bindingHandlers.combo = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize combobox with some optional options
var options = {};
$(element).combobox({
select: function() {
var observable = valueAccessor();
observable($(element).combobox('value'));
}
});
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
var observable = valueAccessor();
observable($(element).val());
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).combobox("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).combobox('value', value);
}
};
})();
</script>
<script>
// jquery.ui.combobox.js
/*!
* Copyright Ben Olson (https://github.com/bseth99/jquery-ui-extensions)
* jQuery UI ComboBox #VERSION
*
* Adapted from Jörn Zaefferer original implementation at
* http://www.learningjquery.com/2010/06/a-jquery-ui-combobox-under-the-hood
*
* And the demo at
* http://jqueryui.com/autocomplete/#combobox
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( $, undefined ) {
$.widget( "ui.combobox", {
options: {
editable: false
},
version: "#VERSION",
widgetEventPrefix: "combobox",
uiCombo: null,
uiInput: null,
_wasOpen: false,
_create: function() {
var self = this,
select = this.element.hide(),
input, wrapper;
input = this.uiInput =
$( "<input />" )
.insertAfter(select)
.addClass("ui-widget ui-widget-content ui-corner-left ui-combobox-input")
.val( select.children(':selected').text() );
wrapper = this.uiCombo =
input.wrap( '<span>' )
.parent()
.addClass( 'ui-combobox' )
.insertAfter( select );
input
.autocomplete({
delay: 0,
minLength: 0,
appendTo: wrapper,
source: $.proxy( this, "_linkSelectList" )
});
$( "<button>" )
.attr( "tabIndex", -1 )
.attr( "type", "button" )
.insertAfter( input )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon ui-combobox-button" );
// Our items have HTML tags. The default rendering uses text()
// to set the content of the <a> tag. We need html().
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).html( item.label ) )
.appendTo( ul );
};
this._on( this._events );
},
_linkSelectList: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), 'i' );
response( this.element.children('option').map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) ) {
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"),
"<strong>$1</strong>"),
value: text,
option: this
};
}
})
);
},
_events: {
"autocompletechange input" : function(event, ui) {
var $el = $(event.currentTarget);
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $el.val() ) + "$", "i" ),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if (!this.options.editable) {
if (!valid) {
// remove invalid value, as it didn't match anything
$el.val("");
this.element.prop('selectedIndex', -1);
//return false;
}
}
}
this._trigger( "change", event, {
item: ui.item ? ui.item.option : null
});
},
"autocompleteselect input": function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
"autocompleteopen input": function ( event, ui ) {
this.uiCombo.children('.ui-autocomplete')
.outerWidth(this.uiCombo.outerWidth(true));
},
"mousedown .ui-combobox-button" : function ( event ) {
this._wasOpen = this.uiInput.autocomplete("widget").is(":visible");
},
"click .ui-combobox-button" : function( event ) {
this.uiInput.focus();
// close if already visible
if (this._wasOpen)
return;
// pass empty string as value to search for, displaying all results
this.uiInput.autocomplete("search", "");
}
},
value: function ( newVal ) {
var select = this.element,
valid = false,
selected;
if (!arguments.length) {
selected = select.children(":selected");
return selected.length > 0 ? selected.val() : null;
}
select.prop('selectedIndex', -1);
select.children('option').each(function() {
if ( this.value == newVal ) {
this.selected = valid = true;
return false;
}
});
if ( valid ) {
this.uiInput.val(select.children(':selected').text());
} else {
this.uiInput.val( "" );
this.element.prop('selectedIndex', -1);
}
},
_destroy: function () {
this.element.show();
this.uiCombo.replaceWith( this.element );
},
widget: function () {
return this.uiCombo;
},
_getCreateEventData: function() {
return {
select: this.element,
combo: this.uiCombo,
input: this.uiInput
};
}
});
}(jQuery));
</script>
Change the select event by change event in your binding handler :
function viewModel() {
var self = this;
self.myOptions = ko.observableArray([{
Name: "First option",
Id: 1
},
{
Name: "Second option",
Id: 2
},
{
Name: "Third option",
Id: 3
}
]);
self.selectedOption = ko.observable(3);
}
var myViewModel = new viewModel();
ko.applyBindings(myViewModel);
<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>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js"></script>
<html>
<body>
<p> Combobox: </p>
<select id="myCombo" data-bind="options: myOptions, optionsText: 'Name', optionsValue: 'Id', value: selectedOption, valueAllowUnset: true, combo: selectedOption"></select>
<p> Option selected Id: </p>
<texarea data-bind="text: selectedOption()"> </texarea>
</body>
</html>
<script>
// ko-combo.js
(function() {
//combobox
ko.bindingHandlers.combo = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize combobox with some optional options
var options = {};
$(element).combobox({
change: function() {
var observable = valueAccessor();
observable($(element).combobox('value'));
}
});
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
var observable = valueAccessor();
observable($(element).val());
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).combobox("destroy");
});
},
//update the control when the view model changes
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).combobox('value', value);
}
};
})();
</script>
<script>
// jquery.ui.combobox.js
/*!
* Copyright Ben Olson (https://github.com/bseth99/jquery-ui-extensions)
* jQuery UI ComboBox #VERSION
*
* Adapted from Jörn Zaefferer original implementation at
* http://www.learningjquery.com/2010/06/a-jquery-ui-combobox-under-the-hood
*
* And the demo at
* http://jqueryui.com/autocomplete/#combobox
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( $, undefined ) {
$.widget( "ui.combobox", {
options: {
editable: false
},
version: "#VERSION",
widgetEventPrefix: "combobox",
uiCombo: null,
uiInput: null,
_wasOpen: false,
_create: function() {
var self = this,
select = this.element.hide(),
input, wrapper;
input = this.uiInput =
$( "<input />" )
.insertAfter(select)
.addClass("ui-widget ui-widget-content ui-corner-left ui-combobox-input")
.val( select.children(':selected').text() );
wrapper = this.uiCombo =
input.wrap( '<span>' )
.parent()
.addClass( 'ui-combobox' )
.insertAfter( select );
input
.autocomplete({
delay: 0,
minLength: 0,
appendTo: wrapper,
source: $.proxy( this, "_linkSelectList" )
});
$( "<button>" )
.attr( "tabIndex", -1 )
.attr( "type", "button" )
.insertAfter( input )
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass( "ui-corner-all" )
.addClass( "ui-corner-right ui-button-icon ui-combobox-button" );
// Our items have HTML tags. The default rendering uses text()
// to set the content of the <a> tag. We need html().
input.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( $( "<a>" ).html( item.label ) )
.appendTo( ul );
};
this._on( this._events );
},
_linkSelectList: function( request, response ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), 'i' );
response( this.element.children('option').map(function() {
var text = $( this ).text();
if ( this.value && ( !request.term || matcher.test(text) ) ) {
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"),
"<strong>$1</strong>"),
value: text,
option: this
};
}
})
);
},
_events: {
"autocompletechange input" : function(event, ui) {
var $el = $(event.currentTarget);
if ( !ui.item ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $el.val() ) + "$", "i" ),
valid = false;
this.element.children( "option" ).each(function() {
if ( $( this ).text().match( matcher ) ) {
this.selected = valid = true;
return false;
}
});
if (!this.options.editable) {
if (!valid) {
// remove invalid value, as it didn't match anything
$el.val("");
this.element.prop('selectedIndex', -1);
//return false;
}
}
}
this._trigger( "change", event, {
item: ui.item ? ui.item.option : null
});
},
"autocompleteselect input": function( event, ui ) {
ui.item.option.selected = true;
this._trigger( "select", event, {
item: ui.item.option
});
},
"autocompleteopen input": function ( event, ui ) {
this.uiCombo.children('.ui-autocomplete')
.outerWidth(this.uiCombo.outerWidth(true));
},
"mousedown .ui-combobox-button" : function ( event ) {
this._wasOpen = this.uiInput.autocomplete("widget").is(":visible");
},
"click .ui-combobox-button" : function( event ) {
this.uiInput.focus();
// close if already visible
if (this._wasOpen)
return;
// pass empty string as value to search for, displaying all results
this.uiInput.autocomplete("search", "");
}
},
value: function ( newVal ) {
var select = this.element,
valid = false,
selected;
if (!arguments.length) {
selected = select.children(":selected");
return selected.length > 0 ? selected.val() : null;
}
select.prop('selectedIndex', -1);
select.children('option').each(function() {
if ( this.value == newVal ) {
this.selected = valid = true;
return false;
}
});
if ( valid ) {
this.uiInput.val(select.children(':selected').text());
} else {
this.uiInput.val( "" );
this.element.prop('selectedIndex', -1);
}
},
_destroy: function () {
this.element.show();
this.uiCombo.replaceWith( this.element );
},
widget: function () {
return this.uiCombo;
},
_getCreateEventData: function() {
return {
select: this.element,
combo: this.uiCombo,
input: this.uiInput
};
}
});
}(jQuery));
</script>

Cannot set property '_renderItem' of undefined with data("ui-autocomplete")

I am having a problem with autocomplete which is keep giving this error and I am unable to figure it out what is causing this issue. I have tried everything on so and still not able to figure it out.
I have bootstrap js and jquery ui also loaded in order of
jquery-1.11.2',
'jquery-ui',
'bootstrap'
$("#search-destination").autocomplete({
minLength: 3,
source: function (request, response) {
var url = "http://localhost/abc/public_html/query/visiting?";
var data = {term: $("#search-destination").val()};
$.getJSON(url, data, function (data) {
// data is an array of objects and must be transformed for autocomplete to use
var array = data.error ? [] : $.map(data.places, function (m) {
var data = {
label: (!isEmpty(m.city)) ? m.title + " (" + m.city + ")" : m.title,
};
return data;
});
response(array);
});
},
focus: function (event, ui) {
},
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
var $a = $("<a></a>").text(item.label);
highlightText(this.term, $a);
return $("<li></li>").append($a).appendTo(ul);
};

Pass Dropdown combobox value with Json auto filling userform

I have a dropdown/combo box, this is how its made
#Html.DropDownList("combobox", Model.Sizes, "--select--")
It uses a jquery ui widget which is,
<script>
(function ($) {
$.widget("custom.combobox", {
_create: function () {
this.wrapper = $("<span>")
.addClass("custom-combobox")
.insertAfter(this.element);
this.element.hide();
this._createAutocomplete();
this._createShowAllButton();
},
_createAutocomplete: function () {
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input = $("<input>")
.appendTo(this.wrapper)
.val(value)
.attr("title", "")
.addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source"),
//ADDED HERE
select: function(event, ui) {
sizeID=ui.item.id;
}
})
.tooltip({
tooltipClass: "ui-state-highlight"
});
this._on(this.input, {
autocompleteselect: function (event, ui) {
ui.item.option.selected = true;
this._trigger("select", event, {
item: ui.item.option
});
},
autocompletechange: "_removeIfInvalid"
});
},
_createShowAllButton: function () {
var input = this.input,
wasOpen = false;
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.tooltip()
.appendTo(this.wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("custom-combobox-toggle ui-corner-right")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// Close if already visible
if (wasOpen) {
return;
}
// Pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(this.element.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text,
value: text,
option: this
};
}));
},
_removeIfInvalid: function (event, ui) {
// Selected an item, nothing to do
if (ui.item) {
return;
}
// Search for a match (case-insensitive)
var value = this.input.val(),
valueLowerCase = value.toLowerCase(),
valid = false;
this.element.children("option").each(function () {
if ($(this).text().toLowerCase() === valueLowerCase) {
this.selected = valid = true;
return false;
}
});
// Found a match, nothing to do
if (valid) {
return;
}
// Remove invalid value
this.input
.val("")
.attr("title", value + " didn't match any item")
.tooltip("open");
this.element.val("");
this._delay(function () {
this.input.tooltip("close").attr("title", "");
}, 2500);
this.input.autocomplete("instance").term = "";
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
$(function () {
$("#combobox").combobox();
$("#toggle").click(function () {
$("#combobox").toggle();
});
});
</script>
I then am trying to pass the value of this dropdown using Json likeeee
<script type="text/javascript">
$(function () {
$("[name='combobox']").change(function () {
$.getJSON('#Url.Action("GetSize")', { sizeID: $("[name='combobox']").val() }, function (Size) {
// Fill the fields according to the Jsondata we requested
$("#KID").val(Size["KammID"]);
This uses the get size action in my controller which is,
public JsonResult GetSize(int sizeID)
{
var Size = db.AllSizes.Find(sizeID);
return Json(Size, JsonRequestBehavior.AllowGet);
}
Andddddd this worked perfectly with my normal dropdown, but once i changed it to a combo box it seems its not getting the sizeID,
HELP BENJI
you could add in a select function as outlined here:
Get value in jquery autocomplete
so when an option is selected you store the value in a variable.
eg:
var sizeID;
.autocomplete({
delay: 0,
minLength: 0,
source: $.proxy(this, "_source"),
select: function(event, ui) {
sizeID=ui.item.id;
}
})

MVC jquery autocomplete multiple values working for first time only

i trying to autocomplete multiple values in my mvc project , but it autocomplete for first value and second nothing occurred
my view code :
#Html.TextBox("SentUsers", "", new { #class = "text-box"})
#Html.Hidden("UsersId")
java script code :
<script type="text/javascript">
var customData = null;
var userId;
$(function () {
$("#SentUsers")
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function (request, response) {
$.ajax({
url: "/Ajax/AutoCompleteUsers",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
alert(data);
customData = $.map(data, function (item) {
userId = item.UserId;
return { label: item.Name + "(" + item.Email + ")", value: item.Name }
});
response(customData, extractLast(request.term))
}
})
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var usersIdVal = $("#UsersId").val();
usersIdVal += ", " + userId;
$("#UsersId").val(usersIdVal)
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;
}
});
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
controller code :
public JsonResult AutoCompleteUsers(string term)
{
var result = (from r in db.UserItems
where r.Name.ToLower().Contains(term.ToLower())
select new { r.Name, r.Email, r.UserId }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
when i trying static javascript array the autocomplete multiple values working perfect !
i think error may be in this block , but i dont know the solution
customData = $.map(data, function (item) {
userId = item.UserId;
return { label: item.Name + "(" + item.Email + ")", value: item.Name }
});
Thanks every body who tried to solve my question , and who isnt, i solved my question, and here is the solution for everybody:
my view code :
#Html.TextBox("SentUsers", "", new { #class = "text-box"})
#Html.Hidden("UsersId")
my javascript code :
<script type="text/javascript">
$(function () {
$("#SentUsers")
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 2,
source: function( request, response ) {
$.getJSON("/Ajax/AutoCompleteUsers", {
term: extractLast( request.term )
}, response );
},
search: function () {
// custom minLength
var term = extractLast(this.value);
if (term.length < 2) {
return false;
}
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var usersIdVal = $("#UsersId").val();
usersIdVal += ", " + ui.item.userId;
$("#UsersId").val(usersIdVal)
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;
}
});
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
my controller code :
public JsonResult AutoCompleteUsers(string term)
{
var result = (from r in db.UserItems
where r.Name.ToLower().Contains(term.ToLower())
select new { label = r.Name + "(" + r.Email + ")", value = r.Name, userId = r.UserId }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}

Jquery AutoComplete with inherited object paramater

I am using jquery-1.9.0 and jquery-ui-1.10.0
var opts = {
source: availableTags
};
var optsA = Object.create(opts,
{
select: {
value: function (event, ui) {}
}
});
var optsB = Object.create(opts,
{
select: {
value: function (event, ui) {}
}
});
$("#tags1").autocomplete(
optsB
);
$("#tags2").autocomplete(
optsA
);
I am trying to build up two seperate arguments lists for my autocompletes. The objects seem to be constructed correctly but the autocomplete doesnt seem to recognise my definition for the select in the inherited objects.
There's a missing property in the Object.create invocation.
You should add enumerable: true
var opts = {
source: availableTags
};
var optsA = Object.create(opts,
{
select: {
value: function (event, ui) {},
enumerable: true
}
});
var optsB = Object.create(opts,
{
select: {
value: function (event, ui) {},
enumerable: true
}
});
$("#tags1").autocomplete(
optsB
);
$("#tags2").autocomplete(
optsA
);
The problem is that the for in loop in jQuery's core extend method can't find the select property because it's not marked as enumerable so that's why it's not accessible from inside the autocomplete.
JSFiddle

Categories