Another application of the above aj ax function is auto-completion. Here we wish to create an input field that expects a month name and, when the visitor types an incomplete name, performs auto-completion via an Ajax request. In response, an auto-completion drop-box appears below the input field. This can be achieved via the following default controller:

1 def month_input():

2 return dict()

4 def month_selector():

5 if not request.vars.month:

7 months = ['January', 'February', 'March', 'April', 'May',

8 'June', 'July', 'August', 'September' , 'October',

11 if m.startswith(request .vars.month.capitalize())]

13 _onclick= "jQuery('#month') .val('is') " % k,

14 _onmouseover= "this, style. backgroundColor= 'yellow' ",

15 _onmouseout= " 'white ' "

and the corresponding "default/monthJnput.html" view:

3 #suggestions { position: relative; }

4 .suggestions { background: white; border: solid 1px #55A6C8; }

5 .suggestions DIV { padding: 2px 4px 2px 4px; }

9 <input type= "text" id= "month" style="width: 250px" /><br />

10 <div style= "position: absolute;" id= "suggestions"

11 class= "suggestions"></div>

13 <script>

The jQuery script in the view triggers the Ajax request each time the visitor types something in the "month" input field. The value of the input field is submitted with the Ajax request to the "month_selector" action. This action finds a list of month names that start with the submitted text (selected), builds a list of DIVs (each one containing a suggested month name), and returns a string with the serialized DIVs. The view displays the response HTML in the "suggestions" DIV. The "month_selector" action generates both the suggestions and the JavaScript code embedded in the DIVs that must be executed when the visitor clicks on each suggestion. For example when the visitor types "Ma" the callback action returns:

1 <div onclick= "jQuery('#month').val('February')"

2 onmouseout=" 'white'"

3 onmouseover=" 'yellow'">February</div>

Here is the final effect:

6 0 6 /i. O Ö ©

est/defauUVmonrh .input

CD 0

O http://127.0.0.l.SQOQ/teil/default/mo



March Mav d by Massimo Di Pierro© auu7, aouS

If the months are stored in a database table such as:

then simply replace the month_seiector action with:

1 def month_input():

2 return dict()

4 def month_selector():

5 it not request.vars.month:

8 selected = [ for row in db(

10 _onclick= "jQuery('#month').val('%s')" % k,

11 _onmouseover= "this, style. backgroundColor= 'yellow' ",

12 _onmouseout= " backgroundColor= ' white ' "

jQuery provides an optional Auto-complete Plugin with additional functionalities, but that is not discussed here.

Was this article helpful?

0 0

Post a comment