Hey there, I'm a total newbie and I'm looking for a way to have a search box with autocomplete just like google does.
I've searched and the best prospect that I've found seems to be http://www.pengoworks.com/workshop/jquery/autocomplete.htm which I found on a forum. The guy who suggested it says he uses it with http://code.google.com/p/searchable-behaviour-for-cakephp/ which is dead on because 开发者_开发百科I've managed to install searchable on my last attempt at figuring out cakephp.
The thing is, I've not used much javascript before and I'm a bit confused as to what exactly I'm meant to be doing. The documentation with the autocomplete codes doesn't go into any detail that I can understand.
If we assume that I manage to get searchable behaviour installed correctly, could any kind person explain to me how I would go about making the autocomplete work?
It says to just use:
$("selector").autocomplete(url [, options]);
eg:
$("#input_box").autocomplete("autocomplete_ajax.cfm");
Autocomplete expects an input element with the id "input_box" to exist. When a user starts typing in the input box, the autocompleter will request autocomplete_ajax.cfm
with a GET parameter named q
thats the bit I don't get. Where am I meant to put that? And once I've put it somewhere then do I just need to name one of my inputs "input_box
"?
thanks in advance.
There are three steps:
1) create a totally normal form with an input field, using the Html helper in your view:
// app/views/foo_bars/search.ctp
<?php
echo $this->Form->create('FooBar');
echo $this->Form->input('field');
echo $this->Form->end('Submit');
?>
2) Have a jquery autocomplete fired:
// app/views/foo_bars/search.ctp
<?php
echo $this->Html->scriptBlock(
.'$("#FooBarField").autocomplete({'
.'source:"/foo_bars/find",'
.'delay: 100,'
.'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
.'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'
.'});'
array('inline' => false));
?>
3) Query a database through a controller to get possible values:
// app/controllers/foo_bars_controller.php
<?php
public function find() {
if ($this->RequestHandler->isAjax()) {
$this->autoLayout = false;
$this->autoRender = false;
$this->FooBar->recursive = -1;
$results = $this->FooBar->find('all', array('fields' => array('id', 'name'), 'conditions' => array('name LIKE "%'.$_GET['term'].'%"')));
$response = array();
$i = 0;
foreach($results as $result){
$response[$i]['value'] = $result['FooBar']['name'];
$response[$i]['id'] = $result['FooBar']['id'];
$i++;
}
echo json_encode($response);
}
}
?>
echo $this->Html->scriptBlock(
'$("#FooBarField").autocomplete({'
.'source:"/Search/find",'
.'delay: 100,'
.'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},'
.'open:function(event,ui){$(this).parent().parent().children("input").val(0);}'
.'});'.
array('inline' => false));
精彩评论