-
Website
http://digitarald.de -
Original page
http://digitarald.de/project/autocompleter/ -
Subscribe
All Comments -
Community
-
Top Commenters
-
RaYz
7 comments · 3 points
-
sim
37 comments · 1 points
-
perrohunter
11 comments · 1 points
-
michalc
8 comments · 1 points
-
digitarald
254 comments · 3 points
-
-
Popular Threads
message: RegExp.prototype.test was called with the wrong number of arguments
stacktrace: ... Line 307 of linked script http://digitarald.de/project/autocompleter/1-1/...
return (tokens || this.tokens).filter(regex.test, regex);
... and so on...
So I've changed line 307 from:
- return (tokens || this.tokens).filter(regex.test, regex);
to the content adapted from 1.0 version:
+ return (tokens || this.tokens).filter(function(token){return regex.test(tokens || this.tokens);});
and all started to work. Thank you digitarald!
I want the working example of this auto completer please can you let me know via email once you have it up and running..i see that you said you will be loading it by next week.....dude_gallary@Hotmail.com
i looked for the working example with all the relevant files but cant find it on your website to download
pls help as i would like to implement this on my personal website
Autocompleter.Base.update() expects the tokens variable to be an array. However, the Json queryResponse method returns a response object. This causes the if statement in update() (around line 269) to break when it checks for length and later when it runs the .each block (around line 273).
The solution is to remove the tokens.length section from the if statement (around line 269) and have the Json queryResponse method return a Hash of the response object.
Line 269 should look like:
if (!tokens) {
Line 422 should look like:
this.update($H(response));
Ideally, there would be a .length method for Hash, but MooTools 1.2 (trunk) doesn't currently have one.
Hope that helps.
missing : after property id
on line
new Autocompleter.Ajax.Json('fe-searchuser', '/test/autocomp.php', {\n
<html>
<head>
link rel="stylesheet" type="text/css" href="Autocompleter.css" />
<style type="text/css">
#demo-local
{
width: 350px;
border: 1px solid #444;
}
</style>
<script type="text/javascript" src="mootools-trunk-1544.js"></script>
<script type="text/javascript" src="Observer.js"></script>
<script type="text/javascript" src="Autocompleter.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
window.addEvent('domready', { new Autocompleter.Ajax.Json('fe-searchuser', '/query_user.php', {'postVar': 'search'}); });
/* ]]> */
</script>
</head>
<body>
<form action="" method="post" id="form-demo">
<input type="text" name="searchuser" id="fe-searchuser"/>
</form>
</body>
</html>
And what is the problem here ?
Thanks!
I am having one difficulty using this new version. I have a form that autocompletes a city. But above the city you are able to choose which country you are in. As the autocomplete url for the city changes depending on the selected country I change the city ajax url when the country changes. Using the old autocompleter I did this by doing "cityAjax.ajax.url = 'new url'. How can I do this with mootools 1.2? "cityAjax.request.url = 'new url' doesn't seem to work.
Thanks for any help!
<%@ WebHandler Language="C#" Class="AutoComplete" %>
using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
public class AutoComplete : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
var result = new List<string>();
result.Add("Cow");
result.Add("Chicken");
context.Response.ContentType = "application/json";
context.Response.Charset = context.Response.ContentEncoding.WebName;
using (var writer = JsonReaderWriterFactory.CreateJsonWriter(context.Response.OutputStream, context.Response.ContentEncoding))
{
var serializer = new DataContractJsonSerializer(typeof(string[]));
serializer.WriteObject(writer, result);
}
}
public bool IsReusable { get { return false; } }
}
I'm getting an error: $empty is not defined (line 29) in both IE and FF.
I just copy the your example “Local Completion”
Txs
Ricardo
The error is now in the mootools beta: Element.implement -> property = property.camelCase(); is not a function (in IE -> this object doesn't support this property or object)
<pre>
window.addEvent('domready', {
new Autocompleter.Ajax.Json('fe-searchuser', '/query_user.php', {
'postVar': 'search'
});
});
</pre>
I get the next error: missing :
*after property id*
window.addEvent('domread', {should be
window.addEvent('domread', function (event) {i am feelin' dumb, but hey i am starting to feel dumber because example tells me to use
[code]
onRequest: indicatorShow,
onRequest: indicatorHide
[/code]
while there is no sign of [b]indicatorShow[/b] or [b]indicatorHide[/b] in the codes. I might feel ok if i could see any showcases since you are telling "check the source of showcases" in almost all paragraphs but i cant see any.
I feel like i'm missing something huge but dont know what
but still constructer is a little different, in Autocompleter.Ajax.Json
Autocompleter.Ajax.Json(searchInput, '/search', {optionsName: optionValue});
should be the correct syntax according to your code
the problem is the separator string .
when I income "tag1, tag2, tag3", the script works perfectly
but when income a space between the first tag and the comma, the script is not working properly
tag1 , tag2 , tag3
What should I do to replace " ," with ","? or, what solution can be applied?
(apologize for my poor English)
I'm looking for a way to show a "searching" icon in the input field while the request is being done.
First, I tried using onRequest, but this doesn't fire early enough for my taste (user may not realize why nothing is happening if he has to wait for the progress icon appears).
Then I tried adding an event to the input fields keypress event, but this fires up the progress icon even if you press the arrow keys/home/end/backspace etc.
onChange is obviously useless as that fires when the field is left out of focus...
Any ideas? Thanks in advance! :-)
One Problem:
I am using Autocompleter.Local
Is it possible to have an array as token? For example search for a word, but as post-data take an id?
this.choices.empty();
this.selected = null;
if (!choices ){
return;
}
if (this.options.maxChoices < choices.length){
choices.length = this.options.maxChoices;
}
for(var i in choices){
var choice = choices[i];
if ((choice!="")&&($type(choice)!='function')){
var el = new Element('li').setHTML(this.markQueryValue(choice));
el.inputValue = choice;
el.id = i;
this.addChoiceEvents(el).injectInside(this.choices);
}
}
this.showChoices();
},
for the 1.0 version, i propose this correction.
You have to delete the .lenght test on line 269
On my mootools 1.11 this correction works nice. (I search how to use ID param)
This is not final code, the id must not be in id param to be XHTML complient.
I have implement new feature to the class :
- if there are more than limit return, the class add a LI with ... to explain this.
- if the param is not an array, but an object, the autocompleter works nice
- the autocompleter give to the user the id selected in the method onSelect.
My new file is on : http://samourais.info/perso/autocompleter/
Don't hesitate to use it or to inspire of it. My companie prefer ta have official release so when we make change on open source file, we are encourage to share our update.
If you type 'a' (or any letter with enough countries that there would be an overflow), if you move your mouse pointer anywhere into the area with the drop down then try to use the down or up arrow key on your keyboard to scroll through the list, instead of scrolling down (or up) through the list to the end, you are jumped back up in the list. If you keep on using your arrow key, you'll eventually get all the way to the end of the list, but you'll be jumped up quite a few times before you do.
Any thoughts on how to fix this?
I tried on IE6 as well as Firefox 3rc1, Firefox 2.0.0.11.
Thanks,
Only got a little problem with the option: overflow:true
In fact, passing over the scroll bar means going out off the autocompleter's div so it closes when passing on a link under this scroll bar...
Someone ever experience the same problem?
Thanks,
BobJpg
Someone ever
but some of my scrips are using the 1.1 version
it's possible to make both work fine ?
the drag and drop don´t work fine for me in the 1.2 version.
thanks a lot for your time !-
I've used your autocompleter to search intor our LDAP directory.
What happens is that I would like to display in suggest list "Firstname, lastname, address,...) and on item click just fill the input textfield with lastname. Something like "option key / value" ...
the javascript
http://paste.mootools.net/f576983de
the php code
http://paste.mootools.net/f548a50b3 ( for the return json )
TIA
but if i use the indicator option i obtain this error from ff:
indicator.show has no properties
http://localhost/ddtrequests/libs/js/autocomple...
Line 382
i use
autcomplete 1.1
mootools trunk 1555
ff2/ie7
winxp
this is my code:
....
<div id="indicatorimg" name="indicatorimg" style="display:none;">
<img style="display:none;" src="images/progress_bar.gif" />
</div>
....
new Autocompleter.Ajax.Json('search_field', './index.php?operation=search', {
'indicator': indicatorimg,
'width': 'auto',
'minLength' : 3,
'maxChoices': 20,
'overflow' : true,
'postVar': 'search_field'
})
thank you for your work and for your help!
Any fix for that?
Thanks a lot
TIA
P.s. but exist some kind of manual, forum, or other example where i can find detailed information ? is really hard to make my modification or addition if i must study the code without documentation... the code is well written but is hard to read every time i need some function.
I try to use the version 1.1.1 (with mootools 1.2 beta 1555) and for the same *<li ...>*, the input is feed with **"Data 1<span>Extra infos</span>** !
Is there any option to correct that ?
i need to pass a value extra in the new auto completer
var autocompleter = new Autocompleter.Ajax.Json( 'ItemName', 'ajax_autoCompleter.php' , {
'postData': { 'field' : 'ItemName' , 'type' : $('selected_type').value }
});
this code works but generate varius autocompleters
i need to redefine postData when some items have a change on the page.
query: function(){
var data = $unlink(this.options.postData);
data[this.options.postVar] = JSON.encode({searchval: this.queryValue, section: getCheckedValue(document.forms['form'].elements['sectionsearch'])});
this.fireEvent('onRequest', [this.element, this.request, data, this.queryValue]);
this.request.send({'data': data});
},
This is the line I change:
data[this.options.postVar] = JSON.encode({searchval: this.queryValue, section: getCheckedValue(document.forms['form'].elements['sectionsearch'])});
It use to be :
data[this.options.postVar] = this.queryValue;
This way it sends a JSON string to your server and from there you can manupulate it.
This what I added to the PHP:
$arrayofpost=json_decode($_POST['searchstring'],true);
$search=$arrayofpost['searchval'];
$section=$search['section'];
I hope it helps... I know its dirty but if your in a hurry like me I should work find.
Thanks for great code.
I'am trying to replicate typical combobox behavior - ie return pairs of {name, id}, show names and get id from the selection. But I don't know where to start.
Should I create 'injectChoice' and 'onSelect' or do I have to change Autocompleter code?
thank You again for Your work,
Robert
I did it with SqueezeBox instead...
But i'am stil curious if it is possible and how. ;)
i need to redefine postdata when some items have a change on the page.
ex:
<input type="text" name="q" id="q" />
<select name="pq" id="pq">
<option value="items1">items1</option>
<option value="items2">items2</option>
</select>
window.addEvent('domready', function() {
new Autocompleter.Ajax.Xhtml($('q'), 'index.php?id=32', {
postData: {'html' : 1, 'pq' : $('pq').value} ,
postVar: 'search',
parseChoices: function(el) {
var value = el.getFirst().innerHTML;
el.inputValue = value;
this.addChoiceEvents(el).getFirst().setHTML(this.markQueryValue(value));
}
});
this code works but generate varius autocompleters
thank for help.
Is there an option and/or event that I can use to automatically submit the selected value with both the mouse click and enter key? I know that autoSubmit will submit correctly with the <enter> key using the keyboard error buttons, so that will work. But, I have been trying different events, specifically the onSelection event which is close, but not exactly right for my needs. The onSelection event works fine with the mouse click, but is not very friendly with the keyboard arrow buttons. It appears that it cancels the autoSubmit option.
I'm looking for a solution to automatically submit using both:
1) the keyboard arrows and submit, AND
2) the mouse with the <enter> key
The autocompleter is just awesome :), thanks.
Good luck with it.
When the choices are shown, the click on a choice does'nt add the default separator ('multiple': true) at the end of line. To speak true, It adds it and remove it just after : I can see the comma, but it desappears fastly.
I'm using mootools 1.2 / firefox 2.0.0.14.
I'm not skilled with mootools, I can just encourage you to test ^^
The problem comes from the autoTrim.
If it's set to false, it works with the mouse.
How can I change the line 213 for preserving separator (the code looks like still doing this, but it does'nt work the way it should.)
Any help ?
thx for reading ^^
Example at:
http://www.icongeneration.com/dev/
Thanks for your work again !
In the <head> I have included the following :-
<script type="text/javascript" src="/media/system/js/mootools.js"></script>
<link rel="stylesheet" href="templates/mymemories/css/Autocompleter.css" type="text/css" />
<script type="text/javascript" src="templates/mymemories/javascript/Observer.js"></script>
<script type="text/javascript" src="templates/mymemories/javascript/Autocompleter.js"></script>
This is my function to get the data to return :-
function getAjaxData()
{
$result = array();
$search = $_POST['q'];
$db =& $this->getDBO();
$query = "SELECT * FROM " . $db->nameQuote('#__jootags_tags')
. " WHERE " . $db->nameQuote('title') . " LIKE '$search%'";
$db->setQuery($query);
$result = $db->loadResultArray();
// return the ajax data
return $result;
}
called from here :-
function display()
{
$ajaxData = $this->get('AjaxData');
$doc =& JFactory::getDocument();
$doc->setMimeEncoding('application/json');
echo json_encode($ajaxData);
}
And this is in my form code :-
<script language="javascript" type="text/javascript">
var searchInput = $('search-field');
// A simple spinner div, display-toggled during request
var indicator = new Element('div', {
'class': 'autocompleter-loading',
'styles': {'display': 'none'}
}).injectAfter(searchInput); // appended after the input
var completer = new Autocompleter.Ajax.Json(searchInput, {
'url': 'index.php?option=com_situploads&view=upload&format=raw',
'postVar': 'q',
'onRequest': function(el) {
indicator.setStyle('display', '');
},
'onComplete': function(el) {
indicator.setStyle('display', 'none');
}
});
</script>
<input type="text" id="search-field"/>
In the <head> I have included the following :-
<script type=”text/javascript” src=”/media/system/js/mootools.js”></script>
<link rel=”stylesheet” href=”templates/mymemories/css/Autocompleter.css” type=”text/css” />
<script type=”text/javascript” src=”templates/mymemories/javascript/Observer.js”></script>
<script type=”text/javascript” src=”templates/mymemories/javascript/Autocompleter.js”></script>
This is my function to get the data to return :-
function getAjaxData() {
$result = array();
$search = $POST[‘q’];
$db =& $this->getDBO();
$query = “SELECT * FROM ” . $db->nameQuote(‘#_jootags_tags’) . ” WHERE ” . $db->nameQuote(‘title’) . ” LIKE ‘$search%’”;
$db->setQuery($query);
$result = $db->loadResultArray();
// return the ajax data
return $result;
}
called from here :-
function display() {
$ajaxData = $this->get(‘AjaxData’);
$doc =& JFactory::getDocument();
$doc->setMimeEncoding(‘application/json’);
echo json_encode($ajaxData);
}
And this is in my form code :-
<script language=”javascript” type=”text/javascript”>
var searchInput = $(‘search-field’);
// A simple spinner div, display-toggled during request var indicator = new Element(‘div’, { ‘class’: ‘autocompleter-loading’, ‘styles’: {‘display’: ‘none’} }).injectAfter(searchInput); // appended after the input
var completer = new Autocompleter.Ajax.Json(searchInput, { ‘url’: ‘index.php?option=com_situploads&view=upload&format=raw’, ‘postVar’: ‘q’, ‘onRequest’: function(el) { indicator.setStyle(‘display’, ”); }, ‘onComplete’: function(el) { indicator.setStyle(‘display’, ‘none’); } });
</script>
The field in the form :-
<input type=”text” id=”search-field”/>
Many thanks,
Mark.
Apologies for the messy posts, please delete them if possible.
Thanks,
Mark.
I try to get this script working but my provider doesn't support "json". I think that instead of using :
new Autocompleter.Ajax.Json
i have to use :
new Autocompleter.Ajax.Base
Then i've tried but it doesn't work, i give my sources:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
<script src="mootools.js" type="text/javascript"></script>
<script src="Observer.js" type="text/javascript"></script>
<script src="Autocompleter.js" type="text/javascript"></script>
<script type="text/javascript">
window.addEvent('domready', function(){
new Autocompleter.Ajax.Base('fe-searchuser',{'postVar': 'searchuser'});
});
</script>
<link rel="stylesheet" type="text/css" href="Autocompleter.css" media="screen" />
</head>
<body>
<form method="POST" action="poster.php">
<input type="text" name="searchuser" id="fe-searchuser" />
</form>
</body>
</html>
poster.php contain:
<?php
include('query_user.php');
if (isset($_POST['search']))
{
$search = $_POST['search'];
}
$result = array();
// Some simple validation
if (is_string($search) && strlen($search) > 2 && strlen($search) < 64)
{
$dbh = new PDO('mysql:host=localhost;dbname=sivoussaviez', $user, $pass);
// Building the query
$stmt = $dbh->prepare("SELECT design FROM sapponia WHERE titre LIKE ?");
// The % as wildcard
if ($stmt->execute(array($search . '%') ) )
{
// Filling the results with usernames
while (($row = $stmt->fetch() ) )
{
$result[] = $row['titre'];
}
}
}
// Finally the JSON, including the correct content-type
//header('Content-type: application/json');
echo $result;
?>
Thank you for your help
I really need it but i am quiet a noob in C#...thank you so much
It works great i just have a couple of questions, first is that there is way to deposit the value generated after the auto complete got a value ?
And also in other version there was an option for partial search, is there something like that now?
Also, there is a way to catch the value that is selected at the end?.
like var completer = new Autocompleter.Local('nombreCampo6', elementosCatalogo6,
{ 'minLength' : 3,
'maxChoices': 20,
'overflow' : true,
'filterSubset' : true,
'delay': 100
}
Thank you in advance
How can i destroy it?
var auto = new Autocompleter.Ajax.Json();
auto.destroy();
This work but i have a Javascript error : this.choice is null on line 267
Thanks for you help
I'm using your tool like in the examples on the page. Everything works, I type something, my php-script sends the right json data and so on. But there's no drop down list!? I can select the different suggestions by using arrow up and down in the input field but I don't get any drop down list to use the mouse or to see all suggestions. What could cause this effect?
Give the element around the input field a "position: relative" and the "ul.autocompleter-choices" a "position: absolute". This worked for me, the drop down list is now under the input field.
I really like your Autocompleter, but I can't seem to find documentation on it! The examples doesn't cover ALL it's features. I think its hard and to figure out all features just browsing your code..
It gets into more detail but to be honest it misses detailed examples. Some functions are still try and error and frustration...
Ths script is good, but it doesnt work with Mootools 1.2 Final, is there an update somewhere ?
Thx
"JavaScript - http://digitarald.de/project/autocompleter/1-1/...
Timeout thread: delay 200 ms
Error:
name: TypeError
message: RegExp.prototype.test was called with the wrong number of arguments
stacktrace: n/a; see 'opera:config#UserPrefs|Exceptions Have Stacktrace'"
Maybe that helps to fix the issue
Don't know why?
PLEASE HELP!
That's the version that was using mootools 1.1
I've tried to get this to work, but it doesn't seem to want to come back. Is there an easy way of doing this, or has this functionality been dropped from this latest moootools1.2 compliant version?
It is a nice script. I have added it in http://www.downloadjavascripts.com. Thanks a lot and keep generating nice stuff !!!!
Now, a quick question, how would one go about submitting more than just the textbox? Say a textbox AND a checkbox?
not work you have to correct
window.addEvent('domready', function() {
// this is wrong
// new Autocompleter.Ajax.Json('fe-searchuser', '/query_user.php', {
// 'postVar': 'search'
// });
var test = new Autocompleter.Ajax.Json('fe-searchuser', 'query_user.php', {
'postVar': 'search'
});
});
How can i do this with php4
["Harald","Haribald","Harold","Harry","Haribald"]
Can U do it?
this.parentNode.getElementsByTagName("span")[0] is undefined
[Break on this error] this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
Im getting this bug in fb console when i click into input which is used for autocompleter. Whats a problem?
Can I use the scripts to control user input? The user should only insert capital letters into a text input field!
Anybody have or seen this issue?
...damn u IE
Im using the autocomplete on an email address - I hit the db - it shows the list populates the field, then in the onSelect event - I take that email - qry the database again based on that email - grab the data and fill the fields I need to w/ that data.
It seems that by using the injectChoice option, I should be able to return a list of ID & email, and when the email is selected, I go into the db w/ that ID and get the data.
Any help would be great. Also- Im limited to this version b/c the site was done w/ mootools 1.11 and we cant upgrade at this time,.
Thanks
I would like to leave a suggestion. The autosuggester would increase its usability if in case doesn't match any result, it notice that.
Thanks!
Script is wonderful, thanks Harald!
xml is null
setSuggestions()(XMLHttpRequest)bsn.Auto..._c_2.0.js (line 308)
onErrorFunc()(XMLHttpRequest)bsn.Auto..._c_2.0.js (line 277)
processReqChange()()bsn.Auto..._c_2.0.js (line 677)
onreadystatechange()()bsn.Auto..._c_2.0.js (line 651)
[Break on this error] var results = xml.getElementsByTagName('results')[0].childNodes;
having read the php code, and since it isn't required to parse a pure xml file, I'm curious as to why there is an xml example, when it's not xml...
it's php generated xml, meaning that the xml file - if a static file is already created - will not functoin....
any suggestions?
from a collection of data which are as follows:
$array(1=>"valorA", 2=>"valorB", 3=>"valorC")
For example if I select "ValorC" requires grab identifier "3"
The object "Select from HTML" allows you to recover the value "3" selecting
"ValorC" from the SELECT html_object.
<select id="colData">
<option value="1">ValorA</option>
<option value="2">ValorB</option>
<option value="3">ValorC</option>
</select>
PLEASE HELP!
from a collection of data which are as follows:
$array(1=>"valorA", 2=>"valorB", 3=>"valorC")
For example if I select "ValorC" requires grab identifier "3"
The object "Select from HTML" allows you to recover the value "3" selecting
"ValorC" from the SELECT html_object.
<select id="colData">
<option value="1">ValorA</option>
<option value="2">ValorB</option>
<option value="3">ValorC</option>
</select>
PLEASE HELP!
line 186:
from:
`'top': pos.bottom,`
to:
`'top': pos.bottom + this.element.getScroll().y,`
my script looks like this:
[code]
new Autocompleter.Request.JSON('fe-search', 'script.php?fkt=GetUser, {
'postVar': 'search'
});
[/code]
a print_r($_REQUEST) gives only a fkt='GetUser'
but the "search" string is missing! what is wrong?
'postData': {
'extended': '1' // send additional POST data, check the PHP code
},
Check the "HTML Request" example.
I changed Autocompleter.js on line 358 to attach the choiceSelect method to the mousedown event instead of the click event and that seems to have fixed it.
Could the blur event have been being fired between mousedown and mouseup?
For some reason i can't seem to get this thing working. It wont show anything when i type in the box, see: http://www.sportwijzer.nl/
the textfield under "Locatie" is the one that should show the suggestions. Please inform me with what is wrong there...
Thanks
richard at korebrits dot nl
reference to undefined property this.options.indicator
[Break on this error] var indicator = $(this.options.indicator);
so how do i fix this??? thanks
var tokens = <?php include("http://example.com/query_file.php"); ?>;
-->
anyone have any ideas on handeling more complex tokens?
When I try set this JSON structure:
{
"type":"full",
"cities":[{"idRegion":"7", "idDistrict":"147", "idCity":"186", "cityName":"Olki"},
{"idRegion":"3", "idDistrict":"247", "idCity":"12351", "cityName":"Olsztyn"}]
}
JavaScript show me error:
tokens.each is not a function
[Break on this error] }, this);
This is places where js put error:
tokens.each(this.options.injectChoice || function(token){
var choice = new Element('li', {'html': this.markQueryValue(token)});
choice.inputValue = token;
this.addChoiceEvents(choice).inject(this.choices);
}, this);
autocompleter.js (linia 270)
What I wrong ?
How I repair it ?
Return something like this from your php script
<li id="your_id">your name</li>
and in your page
var test = new Autocompleter.Request.HTML(....);
test.addEvent('onSelection', mafonction);
function mafonction(a,b,c,d) {
alert(b.id);
}
tokens.each(this.options.injectChoice || function(token){
var choice = new Element('li', {'html': this.markQueryValue(token)});
choice.inputValue = token;
choice.id = ""; // ??????
this.addChoiceEvents(choice).inject(this.choices);
}, this);
code is 266 - 276 lines on acutocompleter.js.
Thanks for interesting my question.
when i try to use the script with the options 'overflow':true in IE6 and IE7:
when i have many suggestion items and i move their selection (using the cursor keys)
to an item that is outside the viewable list, the suggestions dropdown don't jump down and the selected item doesn't appear.
With FF there isn't problem. I try to set the option 'overflowMargin' to different value but the result never change.
Excuse me for my bad english.
Nobody can tell me how to fix this bug? thanks
*To reproduce,*
1. please use your Showcase "Local Tag", and
2. type "a" into the input field,
3. right after press ENTER (to select),
4. and then BACKSPACE (to
The first character "a" of the initially correctly selected entry then get's doubled (i.e. "**a**advertising," instead of "advertising")
I've already spent a few sleepless nights on it, but couldn't find the bug myself... Harald: **heeeeeelp**, please ;))
- Josef
*p.s.: thanks a lot for all your great work here!!!*
Here is once more how to reproduce this bug (IE6 or IE7): Go to the Local Tag showcase at http://digitarald.de/project/autocompleter/1-1/..., then - in the delicious search input - press the following keys: "a", "<ENTER>", then "<BACKSPACE>" - and the first letter gets duplicated... happens only if "type-ahead" and "multiple:true" are configured. Any help would be greatly appreciated!
I have a big problem. I have json array:
<pre>
</pre>var tokens = [{"aaa", "TEXT A", "1234"}, {"aab", "TEXT B", "4321"}, {"aac", "TEXT C", "3421"}];
and HTML Form:
<pre>
</pre><form action="#" method="post">
<input type="hidden" name="ttt" id="ttt" value="" />
<input type="text" name="what" id="what" value="" />
</form>
When I write something to input type text (id="what") I want to show autocomplete list:
"aaa"
"aab"
"aac"
When I choice "aaa" then input type text (id="what") should has "TEXT A" value and input type hidden (id=ttt) should has "1234" value.
How can I do this ???
Please help me !!!
Would it be possible to add ability to display item with description and add to the input field only item?
In example: I'd like to display userName (firstName lastName), but if clicked only userName will be used
The same postVar
text1, text2
How can I correct autocompleter as postVar:cityTip work on first text (text1) but postVar:dupaZimna work on swcond text (text2) ?
Great work.
json
[['ph','Philippines'],['us','United States']]
where the first element is the key and the second is the
value(display purposes), you have to have atleast 2 html elements where one is
a hidden field while the other is the field to be transformed into an
autocompleter
markup
<input type="hidden" name="country_code" id="country_code"/>
<input type="text" name="country_code" id="country_code_autocomplete"/>
script
window.addEvent('domready', function() {
new Autocompleter.Request.JSON('country_code_autocomplete', 'country.php', {
injectChoice: function(token) {
var choice = new Element('li', {
html: this.markQueryValue(token[1])
});
choice.value = token[0];
choice.inputValue = token[1];
this.addChoiceEvents(choice).inject(this.choices);
},
onSelection: function(el, sel) {
$('country_code').set('value', sel.value);
}
}).observer.addEvent('onFired', function(val) {
if(!val)
$('country_code').set('value', '');
});
});
json
`[['ph','Philippines'],['us','United States']]`
where the first element is the key and the second is the
value(display purposes), you have to have atleast 2 html elements where one is
a hidden field while the other is the field to be transformed into an
autocompleter
markup
`<input type="hidden" name="country_code" id="country_code"/>
<input type="text" name="country_code" id="country_code_autocomplete"/>`
script
`window.addEvent('domready', function() {
new Autocompleter.Request.JSON('country_code_autocomplete', 'country.php', {
injectChoice: function(token) {
var choice = new Element('li', {
html: this.markQueryValue(token[1])
});
choice.value = token[0];
choice.inputValue = token[1];
this.addChoiceEvents(choice).inject(this.choices);
},
onSelection: function(el, sel) {
$('country_code').set('value', sel.value);
}
}).observer.addEvent('onFired', function(val) {
if(!val)
$('country_code').set('value', '');
});
});`
Someone said that the Clientcide library fixes it but I've been unable to see how or why.
Can anyone help?
.addEvent('blur' ...
Instead of the removed line you need to type the following:
document.addEvent('click', function(e){
if (e.target != this.choices) this.toggleFocus(false);
}.bind(this));
This prevents losing the focus when clicking the scrollbar. It also fixes that issue for Opera which behaved the same like IE in that case.
The right arguments of Autocompleter.Ajax.Json is (el, url, options) instead of the (el, options).
@ var completer = new Autocompleter.Ajax.Json(searchInput, { ... }
When I'm using Autocompleter with a database, that contains special characters like & and the like, Autocompleter somehow replaces these characters by the html substitution like & for &
How can I turn off this behavior? Though I wont ever find anything in my db this way...
Thanks for the help
David
It will submit the form when you hit enter, while it whould, since the first options is selected.
It doesnt happen with selectFirst: false.
patch - at line 129 of Autocompleter.js:
NOW:
if (this.element.value != this.opted) return true;
PROPOSED PATCH:
if (!this.selected && this.element.value != this.opted) return true;
So it will return true only if there is no selected option, which looks like what it should do.
My version of autocompleter is 1.1.2.
Mootools 1.2.1.
Thanks for the great plugin.
<button onclick="autocompleteObj.???">Click here for list</button>
I am unsre which function will launch the suggestion list?
but one comment ;)
The inicator Option should be better use the 'visibiliy' instead 'display' Parameter because else the Elements on Page 'moving'.
By the way, the data is a list of contacts, so I could get duplicates if I don't have the id and it would screw the rest of my code up.
By the way, the data is a list of contacts, so I could get duplicates if I don't have the id and it would screw the rest of my code up.
is there a way to target the selected word with a different value when the field is submitted?
I'm using a local mode and now when I'm submitting a word "Terms and conditions" it goes to page --> index.php?page=Terms and conditions which doesn't exists. It should be --> index.php?page=terms_and_conditions.
Shouls I give the suggestions-array a second url-value some how or what?
Thanks
In the handler that deals with the onSelect/onSelection could you just replace the spaces with underscores in the input value you're reading before concat'ing it with the url? (Assuming soaces should always be converted to _ of course ;) )
I'm not too familiar with these things, so is there a way you could tell me how to do this excaclty? I'd appriciate that a lot, thanks!
It's going to depend on what your code is currently doing (of which I have no idea :) but something along these line:
function makeURL(theInput, selectedItem, theInputValue, selectedItemValue)
{
var underscoresAdded = selectedItemValue.replace(/ /g,"_");
var myURL = "http://to.somewhere.interesting.com?"+underscoresAdded;
}
and then in your Autocompleter declaration add the 'onSelection:makeURL' handler.
Hope that helps.
window.location = myURL;
as the last statement in makeURL() to make it visit the page obviously ;)
That really gave me a huge help!
Julius
Thanks very much for Autocompleter! One comment/query I had, at present, there doesn't seem to be a way to 'easily' get what the final selected value was. Yes, the onSelect and onSelection will tell you what the current textbox and hovered items are, but not the final choice. Normally this might not be a problem, but I only want to fire an event based on the final choice, and not everytime someone moves over a possible selection.
So, what I did was just add an extra line at the end of the choiceSelect method:
this.fireEvent('onChoice', [this.element, this.selected]);
and then defined my own onChoice handler.
This seems to work fine for my purposes, but I'm still feeling my way around mootools and javascript in general so I could be breaking something I'm unaware of ;)
If you think that's useful or not for a 1.1.3 version, feel free to add it! :)
I'm using this solution, and it works well. I second to add it to the release.
Thanks
The onChoice seems to only work when you use the mouse to select a choice. The onSelect, OnSelection, onBlur happen repeatedly during the user interactions. Is there a trigger that happens when they use the mouse to arrow keys and make a final selection?
Also is there a way to separate the width of the text box from the width of the suggestion box? With wick the suggestion box scaled to the necessary width and did not force the text box to be the same width.
Enabling the tab key is fairly simple. In the onCommand definition just change:
case 'enter':
to
case 'enter': case 'tab':
and similarly remove the case 'tab' for the hideChoices() a few lines further down.
Cheers,
Ben
I'm not too familiar with these things, so is there a way you could tell me how to do this excaclty? I'd appriciate that a lot, thanks!
$results=array("key1"=>$somevalue, "key2"=>$somevalue2);
return json_encode($results);
The correct json was:
$results=array($somevalue, $somevalue2);
It cant be in key/pairs.
However, I need to manage a complete json object, not a simple array. I need to get 2 values (id and string) instead of getting the string only.
Is there a way to do that?
Thanks
var searchbox;
var auto;
document.addEvent('domready', function() {
searchbox = $('my_search);
//instantiate autocompleter
var auto = new Autocompleter.Request.JSON(searchbox, '/verify/search_name', {options});
if(searchbox.get('value') != '')
{
//how do I run autocompleter on the value of searchbox?
}
});
if(searchbox.get('value') != ''){
auto.prefetch();
}
:)
solution, I'd need to know the options you are using.
{
echo 'thnks';
}
I'll try to set up a demo when I have time, but it's a little tricky right now.
result is somthink like this :
alcal�
alcalae�a
alcalae�as
alcalae�os
..
Even a little hint in the right direction would be much appreciated...
I had implemented autocompleter control.
But I need control work like facebook or hotmail compose mail receiver list auto completer control.
It would be great if you provide such a solution using autocompleter.js
I'm running a page on ISo 8859-1 and having problems regarding the german umlaute on a Request.HTML.
For example hitting "nö" is sending "ö" to my php script. the script does the db requests but nothing is found as in the db the entries are "nördlingen" for example. Beside the umlaute the script is working perfect.
Can you help on this topic? Thanks!
Encode::from_to($value, 'utf-8', 'windows-1251');
And it worked.
im having also problems with the encoding using Autocompleter.Request. I've a input text that sends the value for example látex (acute). Then i receive in my java servlet the parameter value l├ít , what its wrong (some king of codec error).
As i read above, with Autocompleter, its seems to reach to the destination request the parameters in UTF-8, but using conversion to ISO-8859-1 ( new String(value.getBytes("ISO-8859-1"), "UTF-8") ) also dosnt work. Can anyone help me with this?
windows xp - firefox 3.0.10 - mootools 1.2.2 - autocompleter 1.1.2
I was wondering if you got a solution for a <select> autocomplete, like some people were saying. It would be useful to me. Thank you!
In query function of Autocompleter.Request we changed the end to
var d = new Hash(data);
if (this.options.supplyFunc != null) d.combine(this.options.supplyFunc());
this.request.send({'data': d});
Ex: if user focus the mouse over the input element, i want to display autocomlpte with all options listed. (for local autocomlpete)
Are here any method for this?
Thanks.
lol = new Autocompleter.Local('category', maincategories, {
'minLength': 0,
'overflow': true,
'filterSubset': true,
'zindex': 50000
});
the important is set minLength to 0!
and your textfield:
<input id="category" name="category" type="text" onfocus="javascript:if(this.value=='') {lol.observer.onFired();}" />
My boss just asked me if I could make the "best bets" and "suggestions" sit side by side but when I did it with floated lists and a customChoices, the placement of the dropdown screwed up.
BTW, I too have noticed the IE6/7 problem with the scrollbar (I turned overflow to false to "solve" it), I was considering extending the duration or playing with the Z-index to fix but haven't had much luck yet.
I'll post my code when it's bedded down and working.
Now all I need to do is make Observer skip over list items that I've applied the choiceHead class to and I'm done!
Very good work, thanks for sharing.
I think your example is not totally correct. The 'url' param is not supposed to be in the options but the second argument of your constructor...
have made the same experience today. The example still isn't fixed:-(
Anyway: You've done a great job, thank you!
Wow, I am liking this functionality big time.
Only issue, and others in this thread are requesting this feature, is how to integrate with a select list instead of a text input field?
I'm going to rig my app to populate a select list on user selection of the typed ahead text, but would be much cleaner to have everything happen in one field (and set the select list value to the ID of the found search term and the display as the search term)
Zoran from Macedonia
(i translitirate my tokens to latin names to get the images)
The code is bad but ain't work in Google Chrome :( it works in FF and IE at the same time! Please help me! How can i include image elements in the result list?
document.addEvent('domready', function() {
// функция транслитерации
function translit(s)
{
var t="аaбbвvгgдdеeёjoжzhзzиiйjjкkлlмmнnоoпpрrсsтtуuфfхkhцcчchшshщshhъ''ыyь'эehюjuяjaАAБBВVГGДDЕEЁJoЖZhЗZИIЙJjКKЛLМMНNОOПPРRСSТTУUФFХKhЦCЧChШShЩShhЪ''ЫYЬ'ЭEhЮJuЯJa";
t=t.replace(/([а-яёЁ])([a-z']+)/gi,'.replace(/$1/g,"$2")');
return eval("s"+t);
}
var tokens = ['Афганистан', 'Aвстралия', 'Албания', 'Алжир', 'Аргентина', 'Ангола', 'Аргентина', 'Армения', 'Аруба', 'Aзербайджан', 'Aвстрия', 'Багамы', 'Бахрейн', 'Бангладеш', 'Барбадос', 'Беларусь', 'Бельгия', 'Белиз', 'Бенин', 'Бермудские острова', 'Бутан', 'Боливия', 'Босния и Герцеговина', 'Ботсвана', 'Буве, остров', 'Бразилия', 'Бруней Дарассалам', 'Болгария', 'Буркина-Фасо', 'Бурунди', 'Бутан', 'Камерун', 'Канада', 'Каймановы о-ва (Великобритания)', 'Центрально-африканская Республика', 'Чад', 'Чили', 'Китай', 'Остров Рождества', 'Кокосовые (Килинг) острова', 'Колумбия', 'Коморские о-ва', 'Конго', 'Демократическая Республика Конго', 'Острова Кука (Новая Зеландия)', 'Коста-Рика', 'Кот-Дивуар', 'Хорватия', 'Куба', 'Кипр', 'Чехия', 'Дания', 'Джибути', 'Доминиканская республика', 'Эквадор', 'Египет', 'Экваториальная Гвинея', 'Эритрия', 'Эстония', 'Эфиопия', 'Фолклендские (Мальвинские) острова', 'Фарерские острова', 'Фиджи', 'Финляндия', 'Франция', 'Французская Гвиана', 'Французская Полинезия', 'Габон', 'Гамбия', 'Грузия', 'Германия', 'Гана', 'Гибралтар', 'Греция', 'Гренландия', 'Гренада', 'Гваделупа', 'Гуам', 'Гватемала', 'Гвинея', 'Гвинея-Бисау', 'Гайна', 'Гаити', 'Гондурас', 'Гон-Конг', 'Венгрия', 'Исландия', 'Индия', 'Индонезия', 'Иран', 'Ирак', 'Ирландия', 'Израиль', 'Италия', 'Ямайка', 'Япония', 'Иордания', 'Казахстан', 'Кения', 'Корея, Южная', 'Корея, Северная', 'Кувейт', 'Киргизстан', 'Лаос', 'Латвия', 'Лесото', 'Либерия', 'Лихтенштейн', 'Литва', 'Люксембург', 'Макао', 'Македония', 'Мадагаскар', 'Малави', 'Малайзия', 'Мальдивы', 'Мали', 'Мальта', 'Мавритания', 'Мексика', 'Микронезия', 'Молдова', 'Монако', 'Монголия', 'Монтсеррат', 'Марокко', 'Мозамбик', 'Мьянма', 'Намибия', 'Непал', 'Нидерланды', 'Новая Каледония', 'Новая Зеландия', 'Никарагуа', 'Нигер', 'Нигерия', 'Норвегия', 'Оман', 'Пакистан', 'Панама', 'Папуа Новой Гвинеи', 'Парагвай', 'Перу', 'Филлипины', 'Польша', 'Португалия', 'Пуэрто-Рико', 'остров Реюньон (Франция)', 'Румыния', 'Российская Федерация', 'Руанда', 'остров Святой Елены', 'Самоа', 'Сан-Марино', 'Саудовская Аравия', 'Сенегал', 'Сьерра-Леоне', 'Сингапур', 'Словакия', 'Словения', 'Соломоновы острова', 'Сомали', 'Южная Африка', 'Испания', 'Шри Ланка', 'Судан', 'Свазиленд', 'Швеция', 'Швейцария', 'Сирия', 'Тайвань', 'Таджикистан', 'Танзания', 'Таиланд', 'Того', 'Токелау', 'Тонга', 'Тринидад и Тобаго', 'Тунис', 'Турция', 'Туркменистан', 'Тувалу', 'Уганда', 'Украина', 'ОАЭ', 'Англия', 'Великобритания', 'США', 'Соединенные Штаты Америки', 'Уругвай', 'Узбекистан', 'Ванауту', 'Венесуэла', 'Вьетнам', 'Йемен', 'Замбия', 'Зимбабве'];
new Autocompleter.Local('demo-local4', tokens, {
'minLength': 1,
'selectMode': 'pick',
'overflow': true,
'injectChoice': function(token){
var choice = new Element('li');
new Element('img', {
'src': 'images/' + translit(token) + '.gif'
}).inject(choice);
new Element('img', {
'src': 'images/' + 'spacer.png'
}).inject(choice);
new Element('span', {'html': this.markQueryValue(token)}).inject(choice);
choice.inputValue = token;
this.addChoiceEvents(choice).inject(this.choices);
}
});
});
Should use another?!?
build: function() {
if ($(this.options.customChoices)) {
this.choices = this.options.customChoices;
this.fix = new OverlayFix(this.choices);
} else {
"this.fix = new OverlayFix(this.choices);" is missing. If you define an own customChoice you will get "this.fix not defined" error later in the source.
Would you mind posting your customChoices code? I'm having a hard time creating a custom choice that has a first part that matches the lookup and then two more values for display only.