Jquery Autocomplete not supported by keyboard - javascript

Autocomplete is not working for keyboard keys but it is working for mouse.i couldnot select item by arrow keys and enter key.
Here is my code. please suggest me any idea. and how to change my selected item background colour in input field?
var triggered = false;
var trigger = "#";
jQuery(".inputbox").autocomplete({
source: function( request, response ) {
var term = request.term;
jQuery.ajax({
url: "/home/friends?q="+term,
dataType: "json",
success: function( data ) {
response( $.map( data, function( item ) {
// alert(item.value);
return {
label: item.name,
value: item.name }
}));
}
});
},
search: function() {
if (!triggered) {
return false;
}
},
select: function(event, ui) {
var text = this.value;
var pos = text.lastIndexOf(trigger);
this.value = text.substring(0, pos + trigger.length) +
ui.item.value;
triggered = false;
return false;
},
focus: function() { return false; },
delay: 0,
minLength: 0,
allowNewTags: false
}).bind("keyup", function() {
var text = this.value;
var len = text.length;
var last;
var query;
var index;
if (triggered) {
index = text.lastIndexOf(trigger);
query = text.substring(index + trigger.length);
$(this).autocomplete("search", query);
}
else if (len >= trigger.length) {
last = text.substring(len - trigger.length);
triggered = (last === trigger);
}
});

I recommend to use https://github.com/ghiden/angucomplete-alt. It have this feature implemented by default.

Related

jquery autocomplete suggest item can't select using keyboard arrow key

this code work perfectly but i can't able to select a item from the suggest list using keyboard up and down key only can select using mouse what's the problem?
please help someone :/ :/ :/
https://jsfiddle.net/g60wc776/
/********************************************************************************
/*
* triggeredAutocomplete (jQuery UI autocomplete widget)
* 2012 by Hawkee.com (hawkee#gmail.com)
*
* Version 1.4.5
*
* Requires jQuery 1.7 and jQuery UI 1.8
*
* Dual licensed under MIT or GPLv2 licenses
* http://en.wikipedia.org/wiki/MIT_License
* http://en.wikipedia.org/wiki/GNU_General_Public_License
*
*/
;(function ( $, window, document, undefined ) {
$.widget("ui.triggeredAutocomplete", $.extend(true, {}, $.ui.autocomplete.prototype, {
options: {
trigger: "#",
allowDuplicates: true
},
_create:function() {
var self = this;
this.id_map = new Object();
this.stopIndex = -1;
this.stopLength = -1;
this.contents = '';
this.cursorPos = 0;
/** Fixes some events improperly handled by ui.autocomplete */
this.element.bind('keydown.autocomplete.fix', function (e) {
switch (e.keyCode) {
case $.ui.keyCode.ESCAPE:
self.close(e);
e.stopImmediatePropagation();
break;
case $.ui.keyCode.UP:
case $.ui.keyCode.DOWN:
if (!self.menu.element.is(":visible")) {
e.stopImmediatePropagation();
}
}
});
// Check for the id_map as an attribute. This is for editing.
var id_map_string = this.element.attr('id_map');
if(id_map_string) this.id_map = jQuery.parseJSON(id_map_string);
this.ac = $.ui.autocomplete.prototype;
this.ac._create.apply(this, arguments);
this.updateHidden();
// Select function defined via options.
this.options.select = function(event, ui) {
var contents = self.contents;
var cursorPos = self.cursorPos;
// Save everything following the cursor (in case they went back to add a mention)
// Separate everything before the cursor
// Remove the trigger and search
// Rebuild: start + result + end
var end = contents.substring(cursorPos, contents.length);
var start = contents.substring(0, cursorPos);
start = start.substring(0, start.lastIndexOf(self.options.trigger));
var top = self.element.scrollTop();
this.value = start + self.options.trigger+ui.item.label+' ' + end;
self.element.scrollTop(top);
// Create an id map so we can create a hidden version of this string with id's instead of labels.
self.id_map[ui.item.label] = ui.item.value;
self.updateHidden();
/** Places the caret right after the inserted item. */
var index = start.length + self.options.trigger.length + ui.item.label.length + 2;
if (this.createTextRange) {
var range = this.createTextRange();
range.move('character', index);
range.select();
} else if (this.setSelectionRange) {
this.setSelectionRange(index, index);
}
return false;
};
// Don't change the input as you browse the results.
this.options.focus = function(event, ui) { return false; }
this.menu.options.blur = function(event, ui) { return false; }
// Any changes made need to update the hidden field.
this.element.focus(function() { self.updateHidden(); });
this.element.change(function() { self.updateHidden(); });
},
// If there is an 'img' then show it beside the label.
_renderItem: function( ul, item ) {
if(item.img != undefined) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + "<img src='" + item.img + "' /><span>"+item.label+"</span></a>" )
.appendTo( ul );
}
else {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" ).text( item.label ) )
.appendTo( ul );
}
},
// This stops the input box from being cleared when traversing the menu.
_move: function( direction, event ) {
if ( !this.menu.element.is(":visible") ) {
this.search( null, event );
return;
}
if ( this.menu.first() && /^previous/.test(direction) ||
this.menu.last() && /^next/.test(direction) ) {
this.menu.deactivate();
return;
}
this.menu[ direction ]( event );
},
search: function(value, event) {
var contents = this.element.val();
var cursorPos = this.getCursor();
this.contents = contents;
this.cursorPos = cursorPos;
// Include the character before the trigger and check that the trigger is not in the middle of a word
// This avoids trying to match in the middle of email addresses when '#' is used as the trigger
var check_contents = contents.substring(contents.lastIndexOf(this.options.trigger) - 1, cursorPos);
var regex = new RegExp('\\B\\'+this.options.trigger+'([\\w\\-]+)');
if (contents.indexOf(this.options.trigger) >= 0 && check_contents.match(regex)) {
// Get the characters following the trigger and before the cursor position.
// Get the contents up to the cursortPos first then get the lastIndexOf the trigger to find the search term.
contents = contents.substring(0, cursorPos);
var term = contents.substring(contents.lastIndexOf(this.options.trigger) + 1, contents.length);
// Only query the server if we have a term and we haven't received a null response.
// First check the current query to see if it already returned a null response.
if(this.stopIndex == contents.lastIndexOf(this.options.trigger) && term.length > this.stopLength) { term = ''; }
if(term.length > 0) {
// Updates the hidden field to check if a name was removed so that we can put them back in the list.
this.updateHidden();
return this._search(term);
}
else this.close();
}
},
// Slightly altered the default ajax call to stop querying after the search produced no results.
// This is to prevent unnecessary querying.
_initSource: function() {
var self = this, array, url;
if ( $.isArray(this.options.source) ) {
array = this.options.source;
this.source = function( request, response ) {
response( $.ui.autocomplete.filter(array, request.term) );
};
} else if ( typeof this.options.source === "string" ) {
url = this.options.source;
this.source = function( request, response ) {
if ( self.xhr ) {
self.xhr.abort();
}
self.xhr = $.ajax({
url: url,
data: request,
dataType: 'json',
success: function(data) {
if(data != null) {
response($.map(data, function(item) {
if (typeof item === "string") {
label = item;
}
else {
label = item.label;
}
// If the item has already been selected don't re-include it.
if(!self.id_map[label] || self.options.allowDuplicates) {
return item
}
}));
self.stopLength = -1;
self.stopIndex = -1;
}
else {
// No results, record length of string and stop querying unless the length decreases
self.stopLength = request.term.length;
self.stopIndex = self.contents.lastIndexOf(self.options.trigger);
self.close();
}
}
});
};
} else {
this.source = this.options.source;
}
},
destroy: function() {
$.Widget.prototype.destroy.call(this);
},
// Gets the position of the cursor in the input box.
getCursor: function() {
var i = this.element[0];
if(i.selectionStart) {
return i.selectionStart;
}
else if(i.ownerDocument.selection) {
var range = i.ownerDocument.selection.createRange();
if(!range) return 0;
var textrange = i.createTextRange();
var textrange2 = textrange.duplicate();
textrange.moveToBookmark(range.getBookmark());
textrange2.setEndPoint('EndToStart', textrange);
return textrange2.text.length;
}
},
// Populates the hidden field with the contents of the entry box but with
// ID's instead of usernames. Better for storage.
updateHidden: function() {
var trigger = this.options.trigger;
var top = this.element.scrollTop();
var contents = this.element.val();
for(var key in this.id_map) {
var find = trigger+key;
find = find.replace(/[^a-zA-Z 0-9#]+/g,'\\$&');
var regex = new RegExp(find, "g");
var old_contents = contents;
contents = contents.replace(regex, trigger+'['+this.id_map[key]+']');
if(old_contents == contents) delete this.id_map[key];
}
$(this.options.hidden).val(contents);
this.element.scrollTop(top);
}
}));
})( jQuery, window , document );
$('#inputbox').triggeredAutocomplete({
hidden: '#hidden_inputbox',
source: [
"Asp",
"BASIC",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
],
trigger: "#"
});
<textarea id='inputbox' style='width: 400px; height: 90px;'></textarea>
<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>

How to check checkbox is checked or not while price slider event occurs

Here is my code,
For price slider:
$("#price-slider").ionRangeSlider({
min: 130,
max: 575,
onChange : function (data) {
var from_num = data.fromNumber;
var to_num =data.toNumber;
$.ajax({
url: 'hotelresults',
type: 'POST',
data: {
from: from_num,
to: to_num,
},
success: function(data){
$('.hotel_list').html(data);
}
});
}
});
When this action occurs I have to check whether the checkboxes are checked or not..
And if it's checked then I need to pass that checked checkbox value in this slider Ajax..
And at the same time its vice versa.
i.e: If the checkbox get checked it should pass the price slider value through its Ajax..
And here is my Checkbox click function
$( ".iCheck-helper" ).on( "click", function(){
var sel = $('.i-check:checked').map(function(_, el) {
return $(el).val();
}).get();
// alert(sel);
var nme = $('.i-check:checked').map(function() {
return $(this).attr("name");
}).get();
// alert(nme);
if(!$(this).is(':checked')){
$.ajax({
type: "POST",
url: "hotelresults",
data: {
key : sel,
name:nme,
},
success: function (data) {
$('.hotel_list').html(data);
}
});
}
});
Both these were pass the values through Ajax..
But I need to pass both values as I said already
Some one help me..
Thanks in advance..
I couldn't test it, but I think it should work. Let me know.
I created an extra function somethingChanged(). When you change your checkBox or RangeSlider, first the chosen values will be put. Then the function with the ajax call will firering.
// Default values
var from_num = 130;
var to_num = 575;
var sel = "";
var nme = "";
function somethingChanged() {
$.ajax({
url: 'hotelresults',
type: 'POST',
data: [
{
from: from_num,
to: to_num
}, {
key: sel,
name: nme
}
],
success: function(data) {
$('.hotel_list').html(data);
}
});
}
$("#price-slider").ionRangeSlider({
min: 130,
max: 575,
onChange: function(data) {
from_num = data.fromNumber;
to_num = data.toNumber;
somethingChanged();
}
});
$(".iCheck-helper").on("click", function() {
sel = $('.i-check:checked').map(function(_, el) {
return $(el).val();
}).get();
nme = $('.i-check:checked').map(function() {
return $(this).attr("name");
}).get();
if (!$(this).is(':checked')) {
somethingChanged();
}
});
Thank you so much NiZa I finally I found it... :)
var from_num = 130;
var to_num = 575;
var sel = "";
var nme = "";
function somethingChanged(from_num,to_num,sel,nme) {
var sel = $('.i-check:checked').map(function(_, el) {
return $(el).val();
}).get();
var nme = $('.i-check:checked').map(function() {
return $(this).attr("name");
}).get();
$.ajax({
url: 'hotelresults',
type: 'POST',
data: {
from: from_num,
to: to_num,
key: sel,
name: nme,
},
success: function(data) {
$('.hotel_list').html(data);
}
});
}
$("#price-slider").ionRangeSlider({
min: 130,
max: 575,
onChange : function (data) {
var from_num = data.fromNumber;
var to_num =data.toNumber;
somethingChanged(from_num,to_num,sel,nme);
}
});
$( ".iCheck-helper" ).on( "click", function(){
var price=$("#price-slider").val();
var myarr = price.split(";");
var from_num = myarr[0];
var to_num = myarr[1];
somethingChanged(from_num,to_num,sel,nme);
});
});
Here, In the checkbox click function I bought the values of priceslider from the priceslider textbox..
And after that I use split and pass those values to the somethingChanged function..
And also In the priceslider event I bought the checked checkbox values from the somethingChanged..
Here, the $('.i-check:checked').map(function(_, el) and $('.i-check:checked').map(function() call every time that both the event occur..

Jquery Close autoComplete list

I have the following JQuery to display an autocomplete list:
var displayNum = 10;
var pointer = displayNum;
function DelegateSearch(txtBox)
{
$("#" + txtBox).attr("placeholder", "Search by Last Name");
$(".ajaxcompanyRefreshImage").attr("src", "/images/refresh.jpg");
$(".ajaxcompanyRefreshImage").hide();
$("#" +txtBox).parents().find('.ajaxcompanyRefreshImage').click(function () { $("#" +txtBox).autocomplete("search"); });
$("#" +txtBox).dblclick(function () { $(this).autocomplete("search"); });
$("#" +txtBox).autocomplete({
change: function (event, ui) {
if ($(this).val() == '') {
$(this).parents().find('.ajaxcompanyRefreshImage').hide();
}
},
close: function (event, ui) {
return false;
},
select: function (event, ui) {
var addr = ui.item.value.split('-');
var label = addr[0];
var value = addr[1];
value += addr[2];
if (label == null || label[1] == null ||(label.length < 1 && value == '' && value.length < 1)) {
$(this).autocomplete("option", "readyforClose", false);
}
else {
if (value[1]!= 0) {
$(this).autocomplete("option", "readyforClose", true);
delegateSearchPostBack(value, label, txtBox);
}
}
return false;
},
response: function (event, ui) {
var more = { label : "<b><a href='javascript:showmoreNames();' id='showmore'>Show more Names...</a></b>", value: '' };
ui.content.splice(ui.content.length, 0, more);
},
open: function(event, ui) {
showmoreNames();
},
search : function (event, ui) {
if ($(this).val().length < 3) {
$(this).parents().find('.ajaxcompanyRefreshImage').hide();
return false;
}
$(".ui-menu-item").remove();
},
source: function (request, response) {
$.ajax({
url: "/ajax/ajaxservice.asmx/GetDelegateListBySearch",
data: "{ prefixText: " + "'" +request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
return data; },
minLength: 2,
success: function (data) {
pointer = displayNum;
response($.map(data.d, function (val, key) {
return {
label: DelegateSearchMenulayout(key, val),
value: val
};
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {}
});
}
});
}
function DelegateSearchMenulayout(key, val) {
var net = '';
var userData = val.split('-');
var table = "<table width=350px' style='border-bottom-style:solid;' class='menutable'>";
table += "<tr><th width='300px'></th>";
table += "<tr><td><b>" + userData[1] + "" + userData[2] + "</b></td></tr>";
table += "<tr><td>" + userData[4] + " - " + userData[3] + "</td></tr>";
table += "</table>";
return table;
}
function delegateSearchPostBack(userName, userId, txtBox) {
$("#" + txtBox).autocomplete("destroy");
$("#" + txtBox).val(userId +"-" + userName );
pointer = displayNum;
__doPostBack(txtBox, "");
}
function showmoreNames() {
$(".menutable").each(function (index) {
if (index >= pointer) {
$(this).parent().hide();
}
else {
$(this).parent().show();
}
});
if ($(".menutable").length <= pointer) {
$("#showmore").attr("href", "javascript: function () {return false;}");
$("#showmore").text("End of Users");
}
else pointer += displayNum;
}
It displays 10 names by default. If the list is longer, "Show more names" is displayed on click of which,10 more names are displayed. With the initial 10 names, the JQuery works perfect.When I click outside or hit ESC, the list of names disappears. But with a longer list, when I click on Show More Names, a longer list is displayed but on click of ESC or clicking outside the list, it does not disappear! How can I make this work?
I tried the following solution:
how to make the dropdown autocomplete to disappear onblur or click outside in jquery?
But with this solution, the list disappears when I click on Show More!
$(document).bind('click', function (event) {
// Check if we have not clicked on the search box
if (!($(event.target).parents().andSelf().is('#showmore'))) {
$(".ui-menu-item").remove();
}
});
The above worked. I did an additional check on document click whether the option 'Show More' is clicked. The has id= 'showmore'. Hence checking if user did not click on it.

Need to access the ID of autocomplete comboBox in jquery

i want to retrive id of Combobox on key event(or on Change:) written below
try to see the CHANGE:function in below code and suggest some tips
i want to retrive id of Combobox on key event(or on Change:) written below
try to see the CHANGE:function in below code and suggest some tips
(function($) {
$.widget("ui.combobox", {
_create: function() {
var input, self = this, select = this.element.hide(), selected = select.children(":selected"), value = selected.val() ?
selected.text() : "", wrapper = this.wrapper =
$("<span>").addClass("ui-combobox").insertAfter(select);
input = $("<input>")
.appendTo(wrapper)
.val(value)
.addClass("ui-state-default ui-combobox-input")
.autocomplete({
delay: 0,
minLength: 0,
source: function(request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function() {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
// alert(text);
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function(event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function(event, ui) {
// alert($(event.target)[0].id);
//alert($(this).attr('id'));
alert(event.target.id);
if (!ui.item) {
xT = $(this).val();
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function() {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
xT = $(this).val();
$(".selPnext").show();
// remove invalid value, as it didn't match anything
// $(this).val("");
// select.val("");
// input.data("autocomplete").term = "";
return false;
}
}
}
})
//.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-combobox-toggle")
.click(function() {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function() {
this.wrapper.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
}); })(jQuery); var xT; function myVal() {
return xT; } $(function() {
//$("#tryy").combobox();
//$("#country").combobox(); });
You can just assign an id to the combobox:
$("<input>").attr('id', 'something')
Then onChange:
$('#something').live('change', function(){
var id = $(this).val();
});

Triggering the return key on event unexpectedly refreshes page and gives undefined error - JavaScript

When I click in field, type text, and press return on keyboard it triggers the initializeTable function that refreshes page and gives error form[0] undefined. However, when I use change event to change dropdown selection, it doesn't cause this unexpected behavior. So I'm not sure why pressing return key in text field is causing all this. Thanks for response.
<script>
(function($){
var listview = $('#listview');
var lists = (function(){
var criteria = {
dropFilter: {
insert: function(value){
if(value)
return {"filter" : value};
},
msg: "Filtering..."
},
searchFilter: {
insert: function(value){
if(value)
return {"search" : value}
},
msg: "Searching..."
}
}
return {
create: function(component){
var component = component.href.substring(component.href.lastIndexOf('#') + 1); //sites
return component;
},
setDefaults: function(component){
var parameter = {};
switch(component){
case "sites":
parameter = {
'url': 'sites',
'order': 'site_num',
'per_page': '20'
}
}
return parameter;
},
getCriteria: function(criterion){
return criteria[criterion];
},
addCriteria: function(criterion, method){
criteria[criterion] = method;
}
}
})();
var Form = function(form){
var fields = [];
$(form[0].elements).each(function(){
var field = $(this);
if(typeof field.attr('alter-data') !== 'undefined') fields.push(new Field(field));
})
}
Form.prototype = {
initiate: function(){
for(field in this.fields){
this.fields[field].calculate();
}
},
isCalculable: function(){
for(field in this.fields){
if(!this.fields[field].alterData){
return false;
}
}
return true;
}
}
var Field = function(field){
this.field = field;
this.alterData = true;
this.component = {'url' : window.location.hash.substring(window.location.hash.indexOf('#') + 1)};
this.attach("change");
this.attach("keypress");
}
Field.prototype = {
attach: function(event){
var obj = this; //our Field object
if(event == "change"){
obj.field.bind("change", function(){
return obj.calculate();
})
}
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
return obj.calculate();
}
})
}
},
calculate: function(){
var obj = this,
field = obj.field,
component = obj.component,
msgClass = "msgClass",
msgList = $(document.createElement("ul")).addClass("msgClass"),
types = field.attr("alter-data").split(" "),
container = field.parent(),
messages = [];
field.next(".msgClass").remove();
for(var type in types){
var criterion = lists.getCriteria(types[type]);
if(field.val()){
var result = criterion.insert(field.val());
container.addClass("waitingMsg");
messages.push(criterion.msg);
obj.alterData = true;
initializeTable(component, result);
}
else {
return false;
obj.alterData = false;
}
}
if(messages.length){
for(msg in messages){
msgList.append("<li>" + messages[msg] + "</li");
}
}
else{
msgList.remove();
}
}
}
$('#dashboard a').click(function(){
var currentComponent = lists.create(this);
var defaults = lists.setDefaults(currentComponent);
initializeTable(defaults);
});
var initializeTable = function(defaults, custom){
var custom = custom || {};
var query_string = $.extend(defaults, custom);
var params = [];
$.each(query_string, function(key,value){
params += key + '=' + value + "&";
})
var url = params.substring(params.indexOf("url")+4,9);
params = params.substring(params.indexOf("&")+1).replace(params.substring(params.lastIndexOf("&")),"");
$.ajax({
type: 'GET',
url: '/' + url,
data: params,
dataType: 'html',
error: function(){},
beforeSend: function(){},
complete: function() {},
success: function(response) {
listview.html(response);
var form = $('form');
form.calculation();
}
})
}
$.extend($.fn, {
calculation: function(){
var formReady = new Form($(this));
if(!formReady.isCalculable){
return false;
}
}
})
})(jQuery)
</script>
Rather than going through whole script, the actual issue is with this:
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
return obj.calculate();
}
})
}
}
Finally, I got it to work this this:
if(event == "keypress"){
obj.field.bind("keypress", function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
return obj.calculate();
}
})
}
},
Hence, we first prevent default and then execute our custom function.

Categories

Resources