and the associated "default/one.html" view:
``
{{extend 'layout.html'}}
<form>
<input name="name" onkeyup="ajax('{{=URL('default', 'echo')}}', ['name'], 'target')" />
</form>
<div id="target"></div>
``:code
and the associated "default/one.html" view:
``
{{extend 'layout.html'}}
<form>
<input name="name" onkeyup="ajax('echo', ['name'], 'target')" />
</form>
<div id="target"></div>
``:code

In jQuery you can refer to the former with the following CSS-like equivalent notations
``
jQuery('.one') // address object by class "one"
jQuery('#a') // address object by id "a"
jQuery('DIV.one') // address by object of type "DIV" with class "one"
jQuery('DIV #a') // address by object of type "DIV" with id "a"
``:code
In jQuery you can refer to the former with the following a CSS-like equivalent notations
``
jQuery('.one') // address object by class "one"
jQuery('#a') // address object by id "a"
jQuery('DIV.one') // address by object of type "DIV" with class "one"
jQuery('DIV #a') // address by object of type "DIV" with id "a"
``:code

Here is an example of how the other effects play well together.
Here is an an example of how the other effects play well together.

and the following "default/index.html" view:
``
{{extend 'layout.html'}}
{{=form}}
<script>
jQuery(document).ready(function(){
+ if(jQuery('#taxpayer_married').prop('checked'))
+ jQuery('#taxpayer_spouse_name__row').show();
+ else jQuery('#taxpayer_spouse_name__row').hide();
jQuery('#taxpayer_married').change(function(){
if(jQuery('#taxpayer_married').prop('checked'))
jQuery('#taxpayer_spouse_name__row').show();
else jQuery('#taxpayer_spouse_name__row').hide();});
});
</script>
``:code
and the following "default/index.html" view:
``
{{extend 'layout.html'}}
{{=form}}
<script>
jQuery(document).ready(function(){
- jQuery('#taxpayer_spouse_name__row').hide();
jQuery('#taxpayer_married').change(function(){
if(jQuery('#taxpayer_married').prop('checked'))
jQuery('#taxpayer_spouse_name__row').show();
else jQuery('#taxpayer_spouse_name__row').hide();});
});
</script>
``:code

While web2py is mainly for server-side development, the **welcome** scaffolding app comes with the base jQuery library``jquery``:cite, jQuery calendars (date picker, datetime picker and clock), and some additional JavaScript functions based on jQuery.
While web2py is mainly for server-side development, the **welcome** scaffolding app comes with the base jQuery library``jquery``:cite, jQuery calendars (date picker, datetime picker and clock), the "superfish.js" menu, and some additional JavaScript functions based on jQuery.

##### Methods and attributes
+- ``jQuery(...).prop(name)``: Returns the name of the attribute value
+- ``jQuery(...).prop(name, value)``: Sets the attribute name to value
- ``jQuery(...).html()``: Without arguments, it returns the inner html from the selected elements, it accepts a string as argument for replacing the tag content.
- ``jQuery(...).text()``: Without arguments, it returns the inner text of the selected element (without tags), if a string is passed as argument, it replaces the inner text with the new data.
- ``jQuery(...).css(name, value)``: With one parameter, it returns the CSS value of the style attribute specified for the selected elements. With two parameters, it sets a new value for the specified CSS attribute.
- ``jQuery(...).each(function)``: It loops trought the selected elements set and calls function with each item as argument.
- ``jQuery(...).index()``: Without arguments, it returns the index value for the first element selected related to its siblings. (i.e, the index of a LI element). If an element is passed as argument, it returns the element position related to the selected elements set.
- ``jQuery(...).length``: This attribute returns the number of elements selected.
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.
Consult the documentation for more information about these effects and other jQuery APIs.
The jQuery library can also be extended using plugins and User Interface Widgets. This topic is not covered here; see ref.``jquery-ui``:cite for details.
#### Conditional fields in forms
A typical application of jQuery effects is a form that changes its appearance based on the value of its fields.
This is easy in web2py because the SQLFORM helper generates forms that are "CSS friendly". The form contains a table with rows. Each row contains a label, an input field, and an optional third column. The items have ids derived strictly from the name of the table and names of the fields.
The convention is that every INPUT field has an id ``tablename_fieldname`` and is contained in a row with id ``tablename_fieldname__row``.
db.define_table('taxpayer',
Field('spouse_name'))
``:code
the following "default.py" controller:
``
def index():
form = SQLFORM(db.taxpayer)
if form.process().accepted:
response.flash = 'record inserted'
return dict(form=form)
``:code
and the following "default/index.html" view:
``
{{extend 'layout.html'}}
{{=form}}
<script>
jQuery(document).ready(function(){
jQuery('#taxpayer_spouse_name__row').hide();
jQuery('#taxpayer_married').change(function(){
if(jQuery('#taxpayer_married').prop('checked'))
jQuery('#taxpayer_spouse_name__row').show();
else jQuery('#taxpayer_spouse_name__row').hide();});
});
</script>
``:code
The script in the view has the effect of hiding the row containing the spouse's name:
[[image @///image/en7500.png center 480px]]
When the taxpayer checks the "married" checkbox, the spouse's name field reappears:
[[image @///image/en7600.png center 480px]]
Here "taxpayer_married" is the checkbox associated to the "boolean" field "married" of table "taxpayer". "taxpayer_spouse_name__row" is the row containing the input field for "spouse_name" of table "taxpayer".
#### Confirmation on delete
``confirmation``:inxx
Another useful application is requiring confirmation when checking a "delete" checkbox such as the delete checkbox that appears in edit forms.
Consider the above example and add the following controller action:
def edit():
row = db.taxpayer[request.args(0)]
form = SQLFORM(db.taxpayer, row, deletable=True)
if form.process().accepted:
response.flash = 'record updated'
return dict(form=form)
``:code
and the corresponding view "default/edit.html"
``
{{extend 'layout.html'}}
{{=form}}
``:code
``deletable``:inxx
The ``deletable=True`` argument in the SQLFORM constructor instructs web2py to display a "delete" checkbox in the edit form. It is ``False`` by default.
web2py's "web2py.js" includes the following code:
``
jQuery(document).ready(function(){
jQuery('input.delete').prop('onclick',
'if(this.checked) if(!confirm(
"{{=T('Sure you want to delete this object?')}}"))
this.checked=false;');
});
``:code
##### Methods and attributes
-- ``jQuery(...).attr(name)``: Returns the name of the attribute value
-- ``jQuery(...).attr(name, value)``: Sets the attribute name to value
- ``jQuery(...).html()``: Without arguments, it returns the inner html from the selected elements, it accepts a string as argument for replacing the tag content.
- ``jQuery(...).text()``: Without arguments, it returns the inner text of the selected element (without tags), if a string is passed as argument, it replaces the inner text with the new data.
- ``jQuery(...).css(name, value)``: With one parameter, it returns the CSS value of the style attribute specified for the selected elements. With two parameters, it sets a new value for the specified CSS attribute.
- ``jQuery(...).each(function)``: It loops trought the selected elements set and calls function with each item as argument.
- ``jQuery(...).index()``: Without arguments, it returns the index value for the first element selected related to its siblings. (i.e, the index of a LI element). If an element is passed as argument, it returns the element position related to the selected elements set.
- ``jQuery(...).length``: This attribute returns the number of elements selected.
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.
Consult the documentation for more information about these effects and other jQuery APIs.
The jQuery library can also be extended using plugins and User Interface Widgets. This topic is not covered here; see ref.``jquery-ui``:cite for details.
#### Conditional fields in forms
A typical application of jQuery effects is a form that changes its appearance based on the value of its fields.
This is easy in web2py because the SQLFORM helper generates forms that are "CSS friendly". The form contains a table with rows. Each row contains a label, an input field, and an optional third column. The items have ids derived strictly from the name of the table and names of the fields.
The convention is that every INPUT field has an id ``tablename_fieldname`` and is contained in a row with id ``tablename_fieldname__row``.
db.define_table('taxpayer',
Field('spouse_name'))
``:code
the following "default.py" controller:
``
def index():
form = SQLFORM(db.taxpayer)
if form.process().accepted:
response.flash = 'record inserted'
return dict(form=form)
``:code
and the following "default/index.html" view:
``
{{extend 'layout.html'}}
{{=form}}
<script>
jQuery(document).ready(function(){
jQuery('#taxpayer_spouse_name__row').hide();
jQuery('#taxpayer_married').change(function(){
if(jQuery('#taxpayer_married').attr('checked'))
jQuery('#taxpayer_spouse_name__row').show();
else jQuery('#taxpayer_spouse_name__row').hide();});
});
</script>
``:code
The script in the view has the effect of hiding the row containing the spouse's name:
[[image @///image/en7500.png center 480px]]
When the taxpayer checks the "married" checkbox, the spouse's name field reappears:
[[image @///image/en7600.png center 480px]]
Here "taxpayer_married" is the checkbox associated to the "boolean" field "married" of table "taxpayer". "taxpayer_spouse_name__row" is the row containing the input field for "spouse_name" of table "taxpayer".
#### Confirmation on delete
``confirmation``:inxx
Another useful application is requiring confirmation when checking a "delete" checkbox such as the delete checkbox that appears in edit forms.
Consider the above example and add the following controller action:
def edit():
row = db.taxpayer[request.args(0)]
form = SQLFORM(db.taxpayer, row, deletable=True)
if form.process().accepted:
response.flash = 'record updated'
return dict(form=form)
``:code
and the corresponding view "default/edit.html"
``
{{extend 'layout.html'}}
{{=form}}
``:code
``deletable``:inxx
The ``deletable=True`` argument in the SQLFORM constructor instructs web2py to display a "delete" checkbox in the edit form. It is ``False`` by default.
web2py's "web2py.js" includes the following code:
``
jQuery(document).ready(function(){
jQuery('input.delete').attr('onclick',
'if(this.checked) if(!confirm(
"{{=T('Sure you want to delete this object?')}}"))
this.checked=false;');
});
``:code

##### Effects
- ``jQuery(...).show()``: Makes the object visible
- ``jQuery(...).hide()``: Makes the object hidden
- ``jQuery(...).slideToggle(speed, callback)``: Makes the object slide up or down
- ``jQuery(...).slideUp(speed, callback)``: Makes the object slide up
- ``jQuery(...).slideDown(speed, callback)``: Makes the object slide down
- ``jQuery(...).fadeIn(speed, callback)``: Makes the object fade in
- ``jQuery(...).fadeOut(speed, callback)``: Makes the object fade out
The speed argument is usually "slow", "fast" or omitted (the default). The callback is an optional function that is called when the effect is completed.
jQuery effects can also easily be embedded in helpers, for example,
in a view:
``
{{=DIV('click me!', _onclick="jQuery(this).fadeOut()")}}
``:code
+Other useful methods and attributes for handling selected elements
+
+##### Methods and attributes
+- ``jQuery(...).attr(name)``: Returns the name of the attribute value
+- ``jQuery(...).attr(name, value)``: Sets the attribute name to value
+- ``jQuery(...).html()``: Without arguments, it returns the inner html from the selected elements, it accepts a string as argument for replacing the tag content.
+- ``jQuery(...).text()``: Without arguments, it returns the inner text of the selected element (without tags), if a string is passed as argument, it replaces the inner text with the new data.
+- ``jQuery(...).css(name, value)``: With one parameter, it returns the CSS value of the style attribute specified for the selected elements. With two parameters, it sets a new value for the specified CSS attribute.
+- ``jQuery(...).each(function)``: It loops trought the selected elements set and calls function with each item as argument.
+- ``jQuery(...).index()``: Without arguments, it returns the index value for the first element selected related to its siblings. (i.e, the index of a LI element). If an element is passed as argument, it returns the element position related to the selected elements set.
+- ``jQuery(...).length``: This attribute returns the number of elements selected.
+
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.
##### Effects
-- ``jQuery(...).attr(name)``: Returns the name of the attribute value
-- ``jQuery(...).attr(name, value)``: Sets the attribute name to value
- ``jQuery(...).show()``: Makes the object visible
- ``jQuery(...).hide()``: Makes the object hidden
- ``jQuery(...).slideToggle(speed, callback)``: Makes the object slide up or down
- ``jQuery(...).slideUp(speed, callback)``: Makes the object slide up
- ``jQuery(...).slideDown(speed, callback)``: Makes the object slide down
- ``jQuery(...).fadeIn(speed, callback)``: Makes the object fade in
- ``jQuery(...).fadeOut(speed, callback)``: Makes the object fade out
The speed argument is usually "slow", "fast" or omitted (the default). The callback is an optional function that is called when the effect is completed.
jQuery effects can also easily be embedded in helpers, for example,
in a view:
``
{{=DIV('click me!', _onclick="jQuery(this).fadeOut()")}}
``:code
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.

"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
- Prevents typing invalid floats in INPUT fields of class "double".
- Connects INPUT fields of type "date" with a popup date picker.
- Connects INPUT fields of type "datetime" with a popup datetime picker.
- Connects INPUT fields of type "time" with a popup time picker.
- Defines ``web2py_ajax_component``, a very important tool that will be described in Chapter 12.
- Defines ``web2py_websocket``, a function that can be used for HTML5 websockets (not described in this book but read the examples in the source of "gluon/contrib/websocket__messaging.py"). ``websockets``:inxx
- Defines functions to the entropy calculation and input validation of the password field.
"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
- Prevents typing invalid floats in INPUT fields of class "double".
- Connects INPUT fields of type "date" with a popup date picker.
- Connects INPUT fields of type "datetime" with a popup datetime picker.
- Connects INPUT fields of type "time" with a popup time picker.
- Defines ``web2py_ajax_component``, a very important tool that will be described in Chapter 12.
- Defines ``web2py_websocket``, a function that can be used for HTML5 websockets (not described in this book but read the examples in the source of "gluon/contrib/websocket__messaging.py"). ``websockets``:inxx
- Defines functions to the entropy calcluation and input validation of the password field.

## jQuery and Ajax
``Ajax``:inxx
While web2py is mainly for server-side development, the **welcome** scaffolding app comes with the base jQuery library``jquery``:cite, jQuery calendars (date picker, datetime picker and clock), the "superfish.js" menu, and some additional JavaScript functions based on jQuery.
Nothing in web2py prevents you from using other
Ajax libraries such as Prototype, ExtJS, or YUI, but we decided to package jQuery because we find it to be easier to use and more powerful than other equivalent libraries. We also find that it captures the web2py spirit of being functional and concise.
### web2py_ajax.html
The scaffolding web2py application "welcome" includes a file called
``
views/web2py_ajax.html
``:code
which looks like this:
``
{{
response.files.insert(0,URL('static','js/jquery.js'))
response.files.insert(1,URL('static','css/calenadar.css'))
response.files.insert(2,URL('static','js/calendar.js'))
response.include_meta()
response.include_files()
}}
<script type="text/javascript"><!--
// These variables are used by the web2py_ajax_init
// function in web2py.js (which is loaded below).
var w2p_ajax_confirm_message =
"{{=T('Are you sure you want to delete this object?')}}";
var w2p_ajax_date_format = "{{=T('%Y-%m-%d')}}";
var w2p_ajax_datetime_format = "{{=T('%Y-%m-%d %H:%M:%S')}}";
//--></script>
<script src="{{=URL('static','js/web2py.js')}}"
type="text/javascript"></script>
``:code
This file is included in the HEAD of the default "layout.html" and it provides the following services:
- Includes "static/jquery.js".
- Includes "static/calendar.js" and "static/calendar.css", which are used for the popup calendar.
- Includes all ``response.meta`` headers
- Includes all ``response.files`` (requires CSS and JS, as declared in the code)
- Sets form variables and includes "static/js/web2y.js"
"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
Here is the "default/list_items.html" view:
{{extend 'layout.html'}}
<form><input type="hidden" id="id" name="id" value="" /></form>
{{for item in items:}}
<p>
<img src="{{=URL('download', args=item.image)}}"
width="200px" />
<br />
Votes=<span id="item{{=item.id}}">{{=item.votes}}</span>
[<span onclick="jQuery('#id').val('{{=item.id}}');
ajax('vote', ['id'], 'item{{=item.id}}');">vote up</span>]
</p>
{{pass}}
``:code
When the visitor clicks on "[vote up]" the JavaScript code stores the item.id in the hidden "id" INPUT field and submits this value to the server via an Ajax request. The server increases the votes counter for the corresponding record and returns the new vote count as a string. This value is then inserted in the target ``item{{=item.id}}`` SPAN.
-------
Ajax callbacks can be used to perform computations in the background, but we recommend using **cron** or a background process instead (discussed in chapter 4), since the web server enforces a timeout on threads. If the computation takes too long, the web server kills it. Refer to your web server parameters to set the timeout value.
-------
-
## jQuery and Ajax
``Ajax``:inxx
While web2py is mainly for server-side development, the **welcome** scaffolding app comes with the base jQuery library``jquery``:cite, jQuery calendars (date picker, datetime picker and clock), the "superfish.js" menu, and some additional JavaScript functions based on jQuery.
Nothing in web2py prevents you from using other
Ajax libraries such as Prototype, ExtJS, or YUI, but we decided to package jQuery because we find it to be easier to use and more powerful than other equivalent libraries. We also find that it captures the web2py spirit of being functional and concise.
### web2py_ajax.html
The scaffolding web2py application "welcome" includes a file called
``
views/web2py_ajax.html
``:code
which looks like this:
``
{{
response.files.insert(0,URL('static','js/jquery.js'))
response.files.insert(1,URL('static','css/calenadar.css'))
response.files.insert(2,URL('static','js/calendar.js'))
response.include_meta()
response.include_files()
}}
<script type="text/javascript"><!--
// These variables are used by the web2py_ajax_init
// function in web2py.js (which is loaded below).
var w2p_ajax_confirm_message =
"{{=T('Are you sure you want to delete this object?')}}";
var w2p_ajax_date_format = "{{=T('%Y-%m-%d')}}";
var w2p_ajax_datetime_format = "{{=T('%Y-%m-%d %H:%M:%S')}}";
//--></script>
<script src="{{=URL('static','js/web2py.js')}}"
type="text/javascript"></script>
``:code
This file is included in the HEAD of the default "layout.html" and it provides the following services:
- Includes "static/jquery.js".
- Includes "static/calendar.js" and "static/calendar.css", which are used for the popup calendar.
- Includes all ``response.meta`` headers
- Includes all ``response.files`` (requires CSS and JS, as declared in the code)
- Sets form variables and includes "static/js/web2y.js"
"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
Here is the "default/list_items.html" view:
{{extend 'layout.html'}}
<form><input type="hidden" id="id" name="id" value="" /></form>
{{for item in items:}}
<p>
<img src="{{=URL('download', args=item.image)}}"
width="200px" />
<br />
Votes=<span id="item{{=item.id}}">{{=item.votes}}</span>
[<span onclick="jQuery('#id').val('{{=item.id}}');
ajax('vote', ['id'], 'item{{=item.id}}');">vote up</span>]
</p>
{{pass}}
``:code
When the visitor clicks on "[vote up]" the JavaScript code stores the item.id in the hidden "id" INPUT field and submits this value to the server via an Ajax request. The server increases the votes counter for the corresponding record and returns the new vote count as a string. This value is then inserted in the target ``item{{=item.id}}`` SPAN.
-------
Ajax callbacks can be used to perform computations in the background, but we recommend using **cron** or a background process instead (discussed in chapter 4), since the web server enforces a timeout on threads. If the computation takes too long, the web server kills it. Refer to your web server parameters to set the timeout value.
-------
-
-

##### Form events
+- ``onchange``: Script to be run when the element changes
+- ``onsubmit``: Script to be run when the form is submitted
+- ``onreset``: Script to be run when the form is reset
+- ``onselect``: Script to be run when the element is selected
+- ``onblur``: Script to be run when the element loses focus
+- ``onfocus``: Script to be run when the element gets focus
##### Keyboard events
+- ``onkeydown``: Script to be run when key is pressed
+- ``onkeypress``: Script to be run when key is pressed and released
+- ``onkeyup``: Script to be run when key is released
##### Mouse events
+- ``onclick``: Script to be run on a mouse click
+- ``ondblclick``: Script to be run on a mouse double-click
+- ``onmousedown``: Script to be run when mouse button is pressed
+- ``onmousemove``: Script to be run when mouse pointer moves
+- ``onmouseout``: Script to be run when mouse pointer moves out of an element
+- ``onmouseover``: Script to be run when mouse pointer moves over an element
+- ``onmouseup``: Script to be run when mouse button is released
Here is a list of useful effects defined by jQuery:
##### Effects
+- ``jQuery(...).attr(name)``: Returns the name of the attribute value
+- ``jQuery(...).attr(name, value)``: Sets the attribute name to value
+- ``jQuery(...).show()``: Makes the object visible
+- ``jQuery(...).hide()``: Makes the object hidden
+- ``jQuery(...).slideToggle(speed, callback)``: Makes the object slide up or down
+- ``jQuery(...).slideUp(speed, callback)``: Makes the object slide up
+- ``jQuery(...).slideDown(speed, callback)``: Makes the object slide down
+- ``jQuery(...).fadeIn(speed, callback)``: Makes the object fade in
+- ``jQuery(...).fadeOut(speed, callback)``: Makes the object fade out
##### Form events
-- onchange: Script to be run when the element changes
-- onsubmit: Script to be run when the form is submitted
-- onreset: Script to be run when the form is reset
-- onselect: Script to be run when the element is selected
-- onblur: Script to be run when the element loses focus
-- onfocus: Script to be run when the element gets focus
##### Keyboard events
-- onkeydown: Script to be run when key is pressed
-- onkeypress: Script to be run when key is pressed and released
-- onkeyup: Script to be run when key is released
##### Mouse events
-- onclick: Script to be run on a mouse click
-- ondblclick: Script to be run on a mouse double-click
-- onmousedown: Script to be run when mouse button is pressed
-- onmousemove: Script to be run when mouse pointer moves
-- onmouseout: Script to be run when mouse pointer moves out of an element
-- onmouseover: Script to be run when mouse pointer moves over an element
-- onmouseup: Script to be run when mouse button is released
Here is a list of useful effects defined by jQuery:
##### Effects
-- jQuery(...).attr(name): Returns the name of the attribute value
-- jQuery(...).attr(name, value): Sets the attribute name to value
-- jQuery(...).show(): Makes the object visible
-- jQuery(...).hide(): Makes the object hidden
-- jQuery(...).slideToggle(speed, callback): Makes the object slide up or down
-- jQuery(...).slideUp(speed, callback): Makes the object slide up
-- jQuery(...).slideDown(speed, callback): Makes the object slide down
-- jQuery(...).fadeIn(speed, callback): Makes the object fade in
-- jQuery(...).fadeOut(speed, callback): Makes the object fade out

Nothing in web2py prevents you from using other
Ajax libraries such as Prototype, ExtJS, or YUI, but we decided to package jQuery because we find it to be easier to use and more powerful than other equivalent libraries. We also find that it captures the web2py spirit of being functional and concise.
### web2py_ajax.html
The scaffolding web2py application "welcome" includes a file called
``
views/web2py_ajax.html
``:code
which looks like this:
``
{{
response.files.insert(0,URL('static','js/jquery.js'))
response.files.insert(1,URL('static','css/calenadar.css'))
response.files.insert(2,URL('static','js/calendar.js'))
response.include_meta()
response.include_files()
}}
<script type="text/javascript"><!--
// These variables are used by the web2py_ajax_init
Here is a list of useful effects defined by jQuery:
- jQuery(...).show(): Makes the object visible
- jQuery(...).hide(): Makes the object hidden
- jQuery(...).slideToggle(speed, callback): Makes the object slide up or down
- jQuery(...).slideUp(speed, callback): Makes the object slide up
- jQuery(...).slideDown(speed, callback): Makes the object slide down
- jQuery(...).fadeIn(speed, callback): Makes the object fade in
- jQuery(...).fadeOut(speed, callback): Makes the object fade out
The speed argument is usually "slow", "fast" or omitted (the default). The callback is an optional function that is called when the effect is completed.
jQuery effects can also easily be embedded in helpers, for example,
in a view:
``
{{=DIV('click me!', _onclick="jQuery(this).fadeOut()")}}
``:code
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.
Consult the documentation for more information about these effects and other jQuery APIs.
The jQuery library can also be extended using plugins and User Interface Widgets. This topic is not covered here; see ref.``jquery-ui``:cite for details.
#### Conditional fields in forms
A typical application of jQuery effects is a form that changes its appearance based on the value of its fields.
This is easy in web2py because the SQLFORM helper generates forms that are "CSS friendly". The form contains a table with rows. Each row contains a label, an input field, and an optional third column. The items have ids derived strictly from the name of the table and names of the fields.
The convention is that every INPUT field has an id ``tablename_fieldname`` and is contained in a row with id ``tablename_fieldname__row``.
As an example, create an input form that asks for a taxpayer's name and for the name of the taxpayer's spouse, but only if he/she is married.
Create a test application with the following model:
``
db = DAL('sqlite://db.db')
db.define_table('taxpayer',
Field('name'),
Field('married', 'boolean'),
Field('spouse_name'))
``:code
and the corresponding view "default/edit.html"
``deletable``:inxx
The ``deletable=True`` argument in the SQLFORM constructor instructs web2py to display a "delete" checkbox in the edit form. It is ``False`` by default.
web2py's "web2py.js" includes the following code:
``
jQuery(document).ready(function(){
jQuery('input.delete').attr('onclick',
'if(this.checked) if(!confirm(
"{{=T('Sure you want to delete this object?')}}"))
this.checked=false;');
});
``:code
By convention this checkbox has a class equal to "delete". The jQuery code above connects the onclick event of this checkbox with a confirmation dialog (standard in JavaScript) and unchecks the checkbox if the taxpayer does not confirm:
[[image @///image/en7700.png center 480px]]
### The ``ajax`` function
In web2py.js, web2py defines a function called ``ajax`` which is based on, but should not be confused with, the jQuery function ``$.ajax``. The latter is much more powerful than the former, and for its usage, we refer you to ref.``jquery``:cite and ref.``jquery-b``:cite. However, the former function is sufficient for many complex tasks, and is easier to use.
Nothing in web2py prevents you from using other
Ajax``ajax:w``:cite libraries such as Prototype, ExtJS, or YUI, but we decided to package jQuery because we find it to be easier to use and more powerful than other equivalent libraries. We also find that it captures the web2py spirit of being functional and concise.
### web2py_ajax.html
The scaffolding web2py application "welcome" includes a file called
``
views/web2py_ajax.html
``:code
which looks like this:
``
{{
response.files.insert(0,URL('static','js/jquery.js'))
response.files.insert(1,URL('static','css/calenadar.css'))
response.files.insert(2,URL('static','js/calendar.js'))
response.include_meta()
response.include_files()
}}
<script type="text/javascript"><!--
// These variables are used by the web2py_ajax_init
Here is a list of useful effects defined by jQuery:
- jQuery(...).show(): Makes the object visible
- jQuery(...).hide(): Makes the object hidden
- jQuery(...).slideToggle(speed, callback): Makes the object slide up or down
- jQuery(...).slideUp(speed, callback): Makes the object slide up
- jQuery(...).slideDown(speed, callback): Makes the object slide down
- jQuery(...).fadeIn(speed, callback): Makes the object fade in
- jQuery(...).fadeOut(speed, callback): Makes the object fade out
The speed argument is usually "slow", "fast" or omitted (the default). The callback is an optional function that is called when the effect is completed.
jQuery effects can also easily be embedded in helpers, for example,
in a view:
``
{{=DIV('click me!', _onclick="jQuery(this).fadeOut()")}}
``:code
jQuery is a very compact and concise Ajax library; therefore web2py does not need an additional abstraction layer on top of jQuery (except for the ``ajax`` function discussed below). The jQuery APIs are accessible and readily available in their native form when needed.
Consult the documentation for more information about these effects and other jQuery APIs.
The jQuery library can also be extended using plugins and User Interface Widgets. This topic is not covered here; see ref.``jquery:ui``:cite for details.
#### Conditional fields in forms
A typical application of jQuery effects is a form that changes its appearance based on the value of its fields.
This is easy in web2py because the SQLFORM helper generates forms that are "CSS friendly". The form contains a table with rows. Each row contains a label, an input field, and an optional third column. The items have ids derived strictly from the name of the table and names of the fields.
The convention is that every INPUT field has an id ``tablename_fieldname`` and is contained in a row with id ``tablename_fieldname__row``.
As an example, create an input form that asks for a taxpayer's name and for the name of the taxpayer's spouse, but only if he/she is married.
Create a test application with the following model:
``
db = DAL('sqlite://db.db')
db.define_table('taxpayer',
Field('name'),
Field('married', 'boolean'),
Field('spouse_name'))
``:code
and the corresponding view "default/edit.html"
``deletable``:inxx
The ``deletable=True`` argument in the SQLFORM constructor instructs web2py to display a "delete" checkbox in the edit form. It is ``False`` by default.
web2py's "web2py.js" includes the following code:
``
jQuery(document).ready(function(){
jQuery('input.delete').attr('onclick',
'if(this.checked) if(!confirm(
"{{=T('Sure you want to delete this object?')}}"))
this.checked=false;');
});
``:code
By convention this checkbox has a class equal to "delete". The jQuery code above connects the onclick event of this checkbox with a confirmation dialog (standard in JavaScript) and unchecks the checkbox if the taxpayer does not confirm:
[[image @///image/en7700.png center 480px]]
### The ``ajax`` function
In web2py.js, web2py defines a function called ``ajax`` which is based on, but should not be confused with, the jQuery function ``$.ajax``. The latter is much more powerful than the former, and for its usage, we refer you to ref.``jquery``:cite and ref.``jquery:b``:cite. However, the former function is sufficient for many complex tasks, and is easier to use.

"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
- Prevents typing invalid floats in INPUT fields of class "double".
- Connects INPUT fields of type "date" with a popup date picker.
- Connects INPUT fields of type "datetime" with a popup datetime picker.
- Connects INPUT fields of type "time" with a popup time picker.
- Defines ``web2py_ajax_component``, a very important tool that will be described in Chapter 12.
+- Defines ``web2py_websocket``, a function that can be used for HTML5 websockets (not described in this book but read the examples in the source of "gluon/contrib/websocket__messaging.py"). ``websockets``:inxx
+- Defines functions to the entropy calcluation and input validation of the password field.
"web2py.js" does the following:
- Defines an ``ajax`` function (based on jQuery $.ajax).
- Makes any DIV of class "error" or any tag object of class "flash" slide down.
- Prevents typing invalid integers in INPUT fields of class "integer".
- Prevents typing invalid floats in INPUT fields of class "double".
- Connects INPUT fields of type "date" with a popup date picker.
- Connects INPUT fields of type "datetime" with a popup datetime picker.
- Connects INPUT fields of type "time" with a popup time picker.
- Defines ``web2py_ajax_component``, a very important tool that will be described in Chapter 12.
-- Defines ``web2py_comet``, a function that can be used for HTML5 websockets (not described in this book but read the examples in the source of "gluon/contrib/comet_messaging.py"). ``websockets``:inxx

It asynchronously calls the url (first argument), passes the values of the field inputs with the name equal to one of the names in the list (second argument), then stores the response in the innerHTML of the tag with the id equal to target (the third argument).
It asynchronously calls the url (first argument), passes the values of the field inputs withthe name equal to one of the names in the list (second argument), then stores the response in the innerHTML of the tag with the id equal to target (the third argument).