jquery ui autocomplete giving an error of "Uncaught TypeError: Cannot read property 'PAGE_UP' of undefined" - jquery-ui

I am trying to use the jquery ui autocomplete, and keep having the following error when you type into the input field that has the autocomplete on it:
Uncaught TypeError: Cannot read property 'PAGE_UP' of undefined
I have included the following files on my page:
jquery-1.7.2.min.js
jquery-ui-1.8.21.custom.min.js
jquery-ui-1.8.21.custom.css
Here is the code using the autocomplete:
$('input#searchFor').autocomplete({
source:function(req,add){
$.getJSON("/index.php/search/autoCompleteHandler?q=?&section="+$('input#searchFor').attr("searchDesc"),req,function(data){
var suggestions = [];
$.each(data,function(i,val){
suggestions.push(val.name);
});
add(suggestions);
});
}
});
I have no idea what could be going wrong. Any help would be appreciated.

The jQueryUI example documentation for a remote data source shows the remote data source should be done like:
$(function() {
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
//the code to execute when an item is clicked on
}
});
});
It looks like source only needs to be a url. You could take a look at the ajax request in Chrome to figure out the $_GET or $_POST variable which is being populated with the search query.
It might not be a bad idea depending on your usage to use the remote data source with caching option.

Related

Jquery UI Autocomplete not working after dom manipluation

I have been trying to implement the autocomplete and have come across a problem that has stumped me. The first time I call .autocomplete it all works fine and I have no problems. If, however, I call it after I have removed some (unrelated) elements from the DOM and added a new section to the DOM then autocomplete does nothing and reports no errors.
Code:-
$.ajax({
type : 'get',
dataType : 'json',
url : '/finance/occupations',
cache:true,
success:function(data){
occupationList = data;
$('.js-occupation').autocomplete({
source: occupationList,
messages: {
noResults: '',
results: function(){}
},
minLength : 2,
select:function(event, ui){
$('.js-occupationId').val(ui.item.id);
}
});
}
});
The background to this page is that it contains multiple sections that are manipulated as the user moves through them. Hide and show works fine and does not impact on the autocomplete. However, if I do the following:-
var section = $('.js-addressForm:last').clone();
clearForm(section);
$('div.addressDetails').append(section);
$('.js-addressForm:first').remove();
Which gives the user the bility to add multiple addresses on the previous section then the autocomplete stops working.
Any suggestions or pointers on something obvious I am missing?
I have tried to put the initialisation of the autocomplete on an event when the element gets focus and it still does not work.
You have to create the autocomplete after all other underlying objects. If you F12, you will see that the list is "visible", however it is below and hidden by all instances created after it.
If you created a div with inputs (one input being the autocomplete), then you create the automplete then the dialog instances, the autocomplete will never show. If you create the dialog then the autocomplete, no problem. The problem is the z-order
I have faced the same issue. For now to fix this, i'm creating widget on the input once input is in focus. It will help you solve the issue.
You can look for the help on
making sure some event bing only when needed
Sample code will look like this
$( "#target" ).focus(function() {
//I don't care if you manipulated the DOM or not. I'll be cautious. ;)
(function() {
$( "#combobox" ).combobox();
$( "#toggle" ).click(function() {
$( "#combobox" ).toggle();
});
})();
// use a flag variable if you want
});
This solved my problem. Hope its the solution you were looking f

What's the event after selecting an entry in jquery autocomplete?

We have a rails 3.2.8 app with jquery autocomplete. The app should fire an event after user selects a customer name from the list (#invoice_customer_name_autocomplete). After selecting, an ajax change event is fired. That's all the app should do. However the following code does not do the job (error: "t.item.customer is undefined"). A user can not even select. The text box won't take customer name and the screen gets stuck:
//for autocomplete
$(function() {
return $('#invoice_customer_name_autocomplete').autocomplete({
minLength: 1,
source: $('#invoice_customer_name_autocomplete').data('autocomplete-source'),
select: function(event, ui) {
$('#invoice_customer_name_autocomplete').val(ui.item.customer.name);
},
});
});
$(document).ready(function (){
$('#invoice_customer_name_autocomplete').change(function (){
//ajax call
$.get(window.location, $('form').serialize(), null, "script");
return false;
});
});
If manually changing the customer name, the .change event will fire. However it does not fire after selecting. What's wrong with the code above?
UPDATE:
If the select can trigger a change event on invoice_customer_name_autocomplete, then this is what we want. Tried the code below without success (no change event fired):
select: function(event, ui) {
$(this).trigger('change');
}
You may be using the jQuery Autocomplete plugin I can't be sure, but you're calling it the way you would call the jQuery UI autocomplete.
In case you are using the first
Suggestions:
Use autocomplete in jQuery UI instead of the autocomplete plugin. The latter is deprecated.
Using the correct framework here is a example of it working:
jsFiddle
It is no different from yours, so the thing is that you should log the ui object in order to understand why you are accessing a null object, the easiest way to do it is to log on console the whole object and watch it.
console.log(ui)
Edit:
Regarding the onChange you may check this post: trigger onchange event manually
Hope it helps!

Jquery Mobile pagecreate function never completes

I am using the pagecreate initialization event to call a function which makes an AJAX call to populate a list.
The problem I have is that this event never completes. The page loading message persists.
I've search here and on the Jquery forum, without any luck.
My code looks like this:
$( "#events" ).live( 'pagecreate', function(event) {
// Executed once the page is loaded
var fromDate = new Date(),
toDate = new Date(fromDate.getFullYear(), fromDate.getMonth() + 3, fromDate.getDate());
update(fromDate, toDate);
//alert('done');
});
function update(from, to) {
var eventList = $('ul#event-list');
$.ajax({
url: 'events.php',
dataType: 'json',
data: {from: from, to: to},
success: function(data) {
showEvents(data, from, to, eventList); // Create list items and append to eventList
$('.value h2').formatCurrency({ negativeFormat: "-%s%n" }); // Format currency correctly using jQuery plugin
}
});
}
I get an "a.Deferred is not a function" error, which suggests to me it has something to do with the completion of the AJAX call, but I've checked, and the showEvents function is correctly creating the list items, so it's not hanging.
After reading this, I tried alternative initialization events: pageinit, and even changePage, without success.
Thanks for your help.
p.s. in case it helps, uncommenting that alert() gets the updated list to reformat correctly, without solving the problem. I figure I'd mention it, since I obviously don't understand what's going on.
If u want to run
the code only once when your project loaded then use
mobileinit. pageshow for every view of page and pagecreate for first
time when pagecreate in your project.

Bind jQuery UI autocomplete using .live()

I've searched everywhere, but I can't seem to find any help...
I have some textboxes that are created dynamically via JS, so I need to bind all of their classes to an autocomplete. As a result, I need to use the new .live() option.
As an example, to bind all items with a class of .foo now and future created:
$('.foo').live('click', function(){
alert('clicked');
});
It takes (and behaves) the same as .bind(). However, I want to bind an autocomplete...
This doesn't work:
$('.foo').live('autocomplete', function(event, ui){
source: 'url.php' // (surpressed other arguments)
});
How can I use .live() to bind autocomplete?
UPDATE
Figured it out with Framer:
$(function(){
$('.search').live('keyup.autocomplete', function(){
$(this).autocomplete({
source : 'url.php'
});
});
});
jQuery UI autocomplete function automatically adds the class "ui-autocomplete-input" to the element. I'd recommend live binding the element on focus without the "ui-autocomplete-input"
class to prevent re-binding on every keydown event within that element.
$(".foo:not(.ui-autocomplete-input)").live("focus", function (event) {
$(this).autocomplete(options);
});
Edit
My answer is now out of date since jQuery 1.7, see Nathan Strutz's comment for use with the new .on() syntax.
If you are using the jquery.ui.autocomplete.js try this instead
.bind("keydown.autocomplete") or .live("keydown.autocomplete")
if not, use the jquery.ui.autocomplete.js and see if it'll work
If that doesn't apply, I don't know how to help you bro
Just to add, you can use the .livequery plugin for this:
$('.foo').livequery(function() {
// This will fire for each matched element.
// It will also fire for any new elements added to the DOM.
$(this).autocomplete(options);
});
To get autocomplete working when loaded dynamically for the on() event used in jQuery > 1.7, using the syntax Nathan Strutz provides in his comment:
$(document).on('focus', '.my-field:not(.ui-autocomplete-input)', function (e) {
$(this).autocomplete(options)
});
where .my-field is a selector for your autocomplete input element.
.live() does not work with focus.
also keyup.autocmplete does not make any sense.
Instead the thing I have tried and working is this
$(document).ready(function(){
$('.search').live('keyup' , function()
{
$(this).autocomplete({ source : 'url.php' });
});
})
This works perfectly fine.
You can't. .live() only supports actual JavaScript events, not any custom event. This is a fundamental limitation of how .live() works.
You can try using this:
$('.foo').live('focus.autocomplete', function() {
$(this).autocomplete({...});
});
After reading and testing everyone else's answers I have updated it for the current version of JQuery and made a few tweaks.
The problem with using keydown as the event that calls .autocomplete() is that it fails to autocomplete for that first letter typed. Using focus is the better choice.
Another thing I have noticed is that all of the given solutions result in .autocomplete() being called multiple times. If you are adding an element dynamically to the page that will not be removed again, the event should only be fired once. Even if the item is to be removed and added again, the event should be removed and then added back each time the element is removed or added so that focusing on the field again will not unnecessarily call .autocomplete() every time.
My final code is as follows:
$(document).on('focus.autocomplete', '#myAutocomplete', function(e){
$(this).autocomplete(autocompleteOptions);
$(document).off('focus.autocomplete', '#myAutocomplete');
});
autocomplete is not an event rather a function that enables autocomplete functionality for a textbox.
So if you can modify the js that creates the textboxes dynamically to wrap the textbox element in as a jquery object and call autocomplete on that object.
I just noticed you edited your post with this answer. It was obvious to me so I'm posting it below for others. Thank you.
$(function()
{
$('.search').live('keyup.autocomplete', function()
{
$(this).autocomplete({ source : 'url.php' });
});
});
This works for me:
$(function()
{
$('.item_product').live('focus.autocomplete', function()
{
$(this).autocomplete("/source.php/", {
width: 550,
matchContains: true,
mustMatch: false,
selectFirst: false,
});
});
});
You can just put the autocomplete inside input live event, like this:
$('#input-element').live('input', function(){
$("#input-element").autocomplete(options);
});

jQuery Autocomplete & jTemplates - handling response

Has anyone had any experience with using jTemplates to display autocomplete results.
I have the following
$("#address-search").autocomplete({
source: "/Address/SearchAddress",
minLength: 2,
delay: 400,
focus: function (event, ui) {
$('#address-search').val(ui.item.name);
return false;
},
parse: function(data) {
$("#autocomplete-results").setTemplate($("#templateHolder").html());
$("#autocomplete-results").processTemplate(data);
},
select: function (event, ui) {
$('#address-search').val(ui.item.name);
$('#search-address-id').val(ui.item.id);
$('#search-description').html(ui.item.address);
});
and the simple jtemplate holder:
<script type="text/html" id="templateHolder">
<ul class="autocomplete">
{#foreach $T as data}
<li>{$T.name}</li>
{#/for}
</ul>
</script>
Above i'm using 'Parse' to format results, I've also tried the autocomplete result method but not having any luck so far. The only success I've had is by using the private method ._renderItem and formatting the data that way but we want to render the output using the jTemplate.
Any advice appreciated.
What kind of issues are you running into? Just looking at your code real quick, it seems like you may not be getting the values you want into the template, or it may be erroring out? Within your foreach, you're calling the individual objects in your array data, but you're appending the value of {$T.name}. Maybe you want {$T.data.name} instead?

Resources