Although the code is very short it does show :
how to change the value of an entry field (INPUT) instead of a block's content (InnerHTML)
how to use the same python callback function for several fields of the same type
how to use links or even clickable text as Ajax "triggers" in addition to form buttons
incrementing and decrementing numbers and dates in text fields
the usefulness of having a third column in SQLFORM :-)
Enjoy,
fpp
from datetime import date, timedelta
from time import mktime, strptime
date_format = "%Y-%m-%d" # in real life this would be read from database or a session variable
def index():
return dict()
def incnum():
numstr = request.vars.values()[0]
return int(numstr) + 1
def decnum():
numstr = request.vars.values()[0]
return int(numstr) - 1
def incdate():
datestr = request.vars.values()[0]
ts = mktime(strptime(datestr , date_format))
newdate = date.fromtimestamp(ts) + timedelta(days=1)
return newdate.strftime(date_format)
def decdate():
datestr = request.vars.values()[0]
ts = mktime(strptime(datestr , date_format))
newdate = date.fromtimestamp(ts) - timedelta(days=1)
return newdate.strftime(date_format)
(the "myajax" function below is the same as in web2py_ajax.html, except that "innerHTML" was replaced by "value" in the last line)
{{extend 'layout.html'}}
<script type="text/javascript"><!--
function myajax(u,s,t) {
var query="";
for(i=0; i<s.length; i++) { if(i>0) query=query+"&";
query=query+encodeURIComponent(s[i])+"="+encodeURIComponent(document.getElementById(s[i]).value);
}
$.ajax({type: "POST", url: u, data: query, success: function(msg) { document.getElementById(t).value=msg; } });
}
//--></script>
<center>
<table>
<tr>
<td>Sales: </td><td><input type="text" id="amount" value="999"></td>
<td>
<input type="submit" id="adec" value="<<" onclick="myajax('{{=URL(r=request,f='decnum')}}',['amount'],'amount');">
<input type="submit" id="ainc" value=">>" onclick="myajax('{{=URL(r=request,f='incnum')}}',['amount'],'amount');">
</td>
</tr>
<tr>
<td>Tax: </td><td><input type="text" id="tax" value="8"></td>
<td>
<a href="#" id="tdec" onclick="myajax('{{=URL(r=request,f='decnum')}}',['tax'],'tax');"><<</a>
<a href="#" id="tinc" onclick="myajax('{{=URL(r=request,f='incnum')}}',['tax'],'tax');">>></a>
</td>
</tr>
<tr>
<td>Date: </td><td><input type="text" id="date" value="2008-02-28"></td>
<td>
<span id="ddec" style="cursor: pointer;" onclick="myajax('{{=URL(r=request,f='decdate')}}',['date'],'date');"><<</span>
<span id="dinc" style="cursor: pointer;" onclick="myajax('{{=URL(r=request,f='incdate')}}',['date'],'date');">>></span>
</td>
</tr>
</table>
(in real life the TABLE would be a SQLFORM using the "3col" argument for the controls)