jQuery
DESCRIPTION
Utilizzo di jQuery con Pylons e altre cosette in JavaScript in genere.
CONFIGURAZIONE
Creare la sottodirectory js in public/ e copiarci i files base jquery-1.3.2.js e jquery-1.3.2.min.js. Il primo deve essere usato per il debug, l'altro in produzione.
Dal template di root, includere i files in questo modo:
${h.tags.javascript_link('/js/jquery-1.3.2.js')}
UTILITY
Per importare on fly un file javascript con jQuery, basta utilizzare
$.getScript('/make_combo.js');
SELECTORS
Il formato base che jQuery supporta per selezionare un certo elemento, consiste in un css selector a cui puo' essere aggiunto opzionalmente un context:
jQuery( expression, [context] )
Ad es, per selezionare un elemento dell'opener da una popup-window:
$('#cognome', window.opener.document);I selectors ritornano un wrapped element set su cui applicare le varie operazioni. I selectors principali hanno una sintassi molto simile ai selectors del css:
- *
- Matches any element.
- E
- Matches all element with tag name E.
- E F
- Matches all elements with tag name F that are descendents of E.
- E>F
- Matches all elements with tag name F that are direct children of E.
- E+F
- Matches all elements F immediately preceded by sibling E.
- E~F
- Matches all elements F preceded by any sibling E.
- E:has(F)
- Matches all elements with tag name E that have at least one descendent with tag name F.
- E.C
- Matches all elements E with class name C. Omitting E is the same as *.C.
- E#I
- Matches element E with id of I. Omitting E is the same as *#I.
- E[A]
- Matches all elements E with attribute A of any value.
- E[A=V]
- Matches all elements E with attribute A whose value is exactly V.
- E[A^=V]
- Matches all elements E with attribute A whose value begins with V.
- E[A$=V]
- Matches all elements E with attribute A whose value ends with V.
- E[A*=V]
- Matches all elements E with attribute A whose value contains V.
Examples
$('table tr[id*="showme"]').hide();
BY POSITION
E' possibile selezionare gli elementi della pagina anche per la posizione nel DOM della pagina stessa. E' importante ricordare che il selector nth-child inizia a contare dall'1, mentre gli altri partono dallo 0:
- :first
- The first match of the page. li a:first returns the first link also under a list item.
- :last
- The last match of the page. li a:last returns the last link also under a list item.
- :first-child
- The first child element. li:first-child returns the first item of each list.
- :last-child
- The last child element. li:last-child returns the last item of each list.
- :only-child
- Returns all elements that have no siblings.
- :nth-child(n)
- The nth child element. li:nth-child(2) returns the second list item of each list.
- :nth-child(even|odd)
- Even or odd children. li:nth-child(even) returns the even children of each list.
- :nth-child(Xn+Y)
- The nth child element computed by the supplied formula. If Y is 0, it may be omitted.
- li:nth-child(3n)
- returns every third item, whereas li:nth-child(5n+1) returns the item after every fifth element.
- :even and :odd
- Even and odd matching elements page-wide. li:even returns every even list item.
- :eq(n)
- The nth matching element.
- :gt(n)
- Matching elements after (and excluding) the nth matching element.
- :lt(n)
- Matching elements before (and excluding) the nth matching element.
CUSTOM JQUERY SELECTORS
Infine ci sono dei selector propri di jQuery, che permettono di selezionare gli elementi di un certo "tipo" o che sono in un certo "stato":
- :animated
- Selects elements that are currently under animated control.
- :button
- Selects any button (input[type=submit], input[type=reset], input[type=button], or button).
- :checkbox
- Selects only check box elements (input[type=checkbox]).
- :checked
- Selects only check boxes or radio buttons that are checked (supported by CSS).
- :contains(foo)
- Selects only elements containing the text foo.
- :disabled
- Selects only form elements that are disabled in the interface (supported by CSS).
- :enabled
- Selects only form elements that are enabled in the interface (supported by CSS).
- :file
- Selects all file elements (input[type=file]).
- :header
Selects only elements that are headers; for example: <h1> through <h6> elements.
- :hidden
- Selects only elements that are hidden.
- :image
- Selects form images (input[type=image]).
- :input
- Selects only form elements (input, select, textarea, button).
- :not(filter)
- Negates the specified filter.
- :parent
- Selects only elements that have children (including text), but not empty elements.
- :password
- Selects only password elements (input[type=password]).
- :radio
- Selects only radio elements (input[type=radio]).
- :reset
- Selects reset buttons (input[type=reset] or button[type=reset]).
- :selected
- Selects option elements that are selected.
- :submit
- Selects submit buttons (button[type=submit] or input[type=submit]).
- :text
- Selects only text elements (input[type=text]).
- :visible
- Selects only elements that are visible.
EACH
Il costrutto each() puo' essere usato sia per selezionare singolarmente gli elementi da un wrapped set, sia come iterator function per iterare sia su di un Array che su di un Object, sia per iterare su di un jQuery Object.
generic iterator - $.each(obj, fn)
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. This function can be used to iterate over anything.
The callback has two arguments:the key (objects) or index (arrays) as first the first, and the value as the second.
jQuery Object iterator - each(fn)
Execute a function within the context of every matched element. This means that every time the passed-in function is executed (which is once for every element matched) the this keyword points to the specific DOM element.
Additionally, the function, when executed, is passed a single argument representing the position of the element in the matched set (integer, zero-index).
MANIPULAING WRAPPED SET
jQuery offre delle funzioni per manipolare il ws sia durante la generazione che dopo la generazione dello stesso. Queste funzioni permettono un controllo granulare degli elementi che andranno a formare il ws su cui lavorare.
MANIPULATE WS
- size()
- Ritorna il numero di elementi nel ws.
- get([index])
Ottiene l'elemento del ws alla posizione index. Se index viene omesso, ritorna tutti gli elementi del ws. In alternativa e' possibile utilizzare anche la sintassi $('img[alt]')[0]. La funzione puo' essere utilizzata anche per ottenere un array JavaScript dal ws:
var allLabeledButtons = $('label+button').get();- index(element)
- Ritorna l'index dell'elemento specificato. Se l'elemento non viene trovato, la funzione ritorna
-1.
ADD REMOVE OR FILTER WS ELEMENTS
- add(expression)
- Adds elements, specified by the expression parameter, to the wrapped set. The expression can be a selector, an HTML fragment, a DOM element, or an array of DOM elements. In jQuery e' possibile ottenre la stessa cosa specificando piu' elementi separati dalla "," nel selettore:
$('img[alt],img[title]')
$('img[alt]').add('img[title]')- not(expression)
- Removes elements from the matched set according to the value of the expression parameter. If the parameter is a jQuery filter selector, any matching elements are removed. If an element reference is passed, that element is removed from the set:
$('img[title]').not('[title*=puppy]')- filter(expression)
- Filters out elements from the wrapped set using a passed selector expression, or a filtering function.
$('td').filter(function(){return this.innerHTML.match(/^\d+$/)})
$('img').addClass('seeThrough').filter('[title*=dog]').addClass('thickBorder')- slice(begin,end)
- Creates and returns a new wrapped set containing a contiguous portion of the matched set.
$('*').slice(2,3);
USE RELATIONSHIPS
- children()
- Returns a wrapped set consisting of all unique children of the wrapped elements.
- contents()
Returns a wrapped set of the contents of the elements, which may include text nodes, in the wrapped set. (Frequently used to obtain the contents of <iframe> elements.)
- next()
- Returns a wrapped set consisting of all unique next siblings of the wrapped elements.
- nextAll()
- Returns a wrapped set containing all the following siblings of the wrapped elements.
- parent()
- Returns a wrapped set consisting of the unique direct parents of all wrapped elements.
- parents()
- Returns a wrapped set consisting of the unique ancestors of all wrapped elements. This includes the direct parents as well as the remaining ancestors all the way up to, but not including, the document root.
- prev()
- Returns a wrapped set consisting of all unique previous siblings of the wrapped elements.
- prevAll()
- Returns a wrapped set containing all the previous siblings of the wrapped elements.
- siblings()
- Returns a wrapped set consisting of all unique siblings of the wrapped elements.
OTHER FUNCTIONS
- find(selector)
- Returns a new wrapped set containing all elements of the original set that match the passed selector expression. Is the same of:
wrappedSet.find('p cite')
$('p cite',wrappedSet)- contains(text)
- returns a new wrapped set composed of elements that contain the text string passed as the text parameter.
$('p').contains('Lorem ipsum')- is(selector)
- Determines if any element in the wrapped set matches the passed selector expression.
var hasImage = $('*').is('img');
WS CHAINING
- end()
- Used within a chain of jQuery command to back up the wrapped set to a previously returned set.
- andSelf()
- Merges the two previous wrapped sets in a command chain.
We've made a big deal (and will continue to do so, because it is a big deal) about the ability to chain jQuery wrapper methods together to perform a lot of activity in a single statement. This chaining ability not only allows us to write powerful operations in a concise manner, but it also improves efficiency because wrapped sets do not have to be recomputed in order to apply multiple commands to them.
Depending upon the methods used in a command chain, multiple wrapped sets may be generated. For example, using the clone() method generates a new wrapped set, which creates copies of the elements in the first set.
If, once a new wrapped set is generated, we had no way to reference the original set, our ability to construct versatile jQuery command chains would be curtailed. Consider the following statement:
$('img').clone().appendTo('#somewhere');Two wrapped sets are generated within this statement: the original wrapped set of all the <img> elements on a page and a second wrapped set consisting of copies of those elements. The clone() method returns this second set as its result, and it's that set that's operated on by the appendTo() command.
But what if we subsequently want to apply a command, such as adding a class name, to the original wrapped set after it's been cloned? We can't tack it onto the end of the existing chain; that would affect the clones, not the original wrapped set of images.
jQuery provides for this need with the end() command. This method, when used within a jQuery chain, will back up to a previous wrapped set and return it as its value so that subsequent operations will apply to the previous set. Consider
$('img').clone().appendTo('#somewhere').end().addClass('beenCloned');The appendTo() method returns the set of new clones, but by calling end() we back up to the previous wrapped set (the original images), which gets operated on by the addClass() command. Without the intervening end() command, addClass() would have operated on the set of clones.
It might help to think of the wrapped sets generated during a jQuery command chain as being held on a stack. When end() is called, the topmost (most recent) wrapped set is popped from the stack, leaving the previous wrapped set exposed for subsequent commands to operate upon.
Another handy jQuery method that modifies the wrapped set stack is andSelf(), which merges the two topmost sets on the stack into a single wrapped set.
EVENTS
jQuery implementa dei metodi cross-browser per implementare la gestione degli eventi. La funzione principale per collegare un elemento del DOM con una funzione richiamata allo scatenarsi di un evento e' bind().
bind(eventType,data,listener)
Establishes a function as the event handler for the specified event type on all elements in the matched set.
- eventType (String)
- Specifies the name of the event type for which the handler is to be established. This event type can be namespaced with a suffix separated from the event name with a period character.
- data (Object)
- Caller-supplied data that's attached to the Event instance as a property named data for availability to the handler functions. If omitted, the handler function can be specified as the second parameter.
- listener (Function)
- The function that's to be established as the event handler.
events type
jQuery supporta gli eventi standard del DOM, utilizzabili con bind() per collegare l'evento ad una funzione:
- * 3
blur
- * 3
change
- * 3
click
- * 3
dblclick
- * 3
error
- * 3
focus
- * 3
keydown
- * 3
keypress
- * 3
keyup
- * 3
load
- * 3
mousedown
- * 3
mousemove
- * 3
mouseout
- * 3
mouseover
- * 3
mouseup
- * 3
resize
- * 3
scroll
- * 3
select
- * 3
submit
- * 3
unload
Event instance properties
- altKey
Set to true if the Alt key was pressed when the event was triggered, false if not.
The Alt key is labeled Option on most Mac keyboards.
- ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not.
- data
The value, if any, passed as the second parameter to the bind() command when the
handler was established.
- keyCode
For keyup and keydown events, this returns the key that was pressed. Note that for
alphabetic characters, the uppercase version of the letter will be returned, regardless
of whether the user typed an uppercase or lowercase letter. For example, both a and A
will return 65. You can use shiftKey to determine which case was entered. For keypress
events, use the which property, which is reliable across browsers.
- metaKey
Set to true if the Meta key was pressed when the event was triggered, false if not.
The Meta key is the Ctrl key on PCs and the Command key on Macs.
- pageX
For mouse events, specifies the horizontal coordinate of the event relative from the
page origin.
- pageY
For mouse events, specifies the vertical coordinate of the event relative from the page
origin.
- relatedTarget
For some mouse events, identifies the element that the cursor left or entered when
the event was triggered.
- screenX
For mouse events, specifies the horizontal coordinate of the event relative from the
screen origin.
- screenY
For mouse events, specifies the vertical coordinate of the event relative from the
screen origin.
- shiftKey
Set to true if the Shift key was pressed when the event was triggered, false if not.
target Identifies the element for which the event was triggered.
- target
Identifies the element for which the event was triggered.
- type
For all events, specifies the type of event that was triggered (for example, click). This
can be useful if you\u2019re using one event handler function for multiple events.
- which
For keyboard events, specifies the numeric code for the key that caused the event,
and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3
for right). This should be used instead of button, which can\u2019t be relied on to function
consistently across browsers.
AJAX
Per richiamare in maniera asincrona una funzione lato server, si utilizza la sintassi:
<script type="text/javascript">
$(document).ready(function() {
$('#cognome').change(function(event) {
$.ajax({
type: 'POST',
url: '/json_data/get_data',
dataType: 'json',
data: {
qry: this.value
},
success: function(retval, textStatus) {
$('#cognome').val('hai immesso: '+retval.data);
alert(retval.data+' => '+textStatus);
}
});
});
});
</script>
submit di un form
Per effettuare il submit di un form senza dover poi ricaricare la pagina, si puo' usare
$.ajax e la funzione
serializeArray() di jquery:
<script type="text/javascript">
$(document).ready(function() {
//
// blocca il submit del form e lo esegue via ajax
//
$('#vt').bind('submit', function(event) {
$.ajax({
url: '/varturnistica/save_data',
type: 'post',
dataType: 'json',
data: $(this).serializeArray(),
success: function(retval, textStatus) {
alert(retval.data);
$('#varturnistica').html('');
}
});
return false;
});
});
</script>
${h.tags.form(url='', id='vt')}
<table class="tform">
<tr>
<td><label for="assente">marittimo assente</label></td>
<td>${h.tags.select('assente', None, c.marittimi, id='assente')}</td>
</tr>
<tr>
<td><label for="sostituto">sostituto</label></td>
<td>${h.tags.text('sostituto', size=40)}</td>
${h.tags.hidden('sostituto_id', id='sostituto_id')}
</tr>
<tr>
<td><label for="descr">causa sostituzione</label></td>
<td>${h.tags.textarea('descr', cols=60, rows=3)}</td>
</tr>
<tr>
<td colspan="2">${h.tags.submit('button', 'Sent')}</td>
${h.tags.hidden('turno', id='turno', value=c.turno)}
</tr>
</table>
${h.tags.end_form()}
download di un file
Se dobbiamo scaricare un file da un controller, possiamo utilizzare un
iframe e la funzione
.load() di jquery:
$(document).ready(function() {
...
$('#ex').bind('submit', function(event) {
$('#downloadFrame').attr('src', '/reporting/ex172/print_pdf?'+$(this).serialize());
return false;
});
...
});
${h.tags.form(url='', id='ex')}
<table class="tsmall">
<tr>
<td><label for="start">selezionare la data</label></td>
<td>${h.tags.text('start', id='start', size=10)}</td>
</tr>
<tr>
<td colspan="2">
${h.tags.submit('slct', 'mostra turni')}
</td>
</tr>
</table>
${h.tags.end_form()}
<iframe id="downloadFrame" src="" style="visibility:hidden"></iframe>
AUTOCOMPLETE PLUGIN
Questo plugin permette di creare un campo di testo che si autocompleta con i dati ritornati
in maniera asincrona dal server. Per utilizzare il plugin, bisogna includere i files:
${h.tags.stylesheet_link('/css/jquery.autocomplete.css')}
${h.tags.javascript_link('/js/jquery.autocomplete.js')}
dati locali
<script type="text/javascript">
$(document).ready(function(){
var data = "Core Selectors Attributes Traversing CSS Events Ajax Utilities".split(" ");
$("#example").autocomplete(data);
});
</script>
API Reference: <input id="example" />
parse dei dati stringa
Il metodo standard di parsare i dati e'
parse(), che splitta la stringa ritornata dal server, suddividendo le row con il carattere
di \(lq\\n\(rq e le columns con il carattere \(lq|\(rq:
jQuery
function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
// il risultato da mostrare nell'input
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};Pylons
def get_nave(self):
_qry = request.params.get('q')
log.debug(_qry)
return '1|uno\n2|due\n3|tre\n'
parse dei dati JSON
Per formattare i dati ritornati in formato JSON dal server bisogna riscrivere il metodo
parse:
jQuery
$('#nave').autocomplete(
'/json_data/cb_navi', {
parse: function(data) {
return $.map(eval(data), function(row) {
return {
data: row.id+'#'+row.showme,
value: row.showme,
result: row.showme
}
});
},
formatItem: function(item, i) {
return item.split('#')[1];
}
}
).result(function(event, data, formatted) {
var myid = data.split('#')[0];
$('#nave_id').val(myid);
});Pylons
@jsonify
def cb_navi(self):
_search = request.params.get('q')
if not _search:
return
_search += '%'
with db.Db() as _crs:
_crs.execute('''SELECT codnave AS id,
CASE WHEN naz IS NOT NULL THEN
nome||' ('|| stazza || ') - '||naz
ELSE
nome||' ('|| stazza || ')'
END AS showme
FROM navi WHERE nome ILIKE %(search)s
ORDER BY nome, stazza''', dict(search = _search))
_retval = _crs.fetchall()
return _retval
autocomplete(url or data)
Rende un campo
input od una
textarea autocompletabile. Nel caso si utilizzino dei dati remoti, quando si inizia a scrivere
nel campo, viene fatta una richiesta al server creando un parametro
GET chiamato
q che contiene il valore immesso, e un parametro
limit, con il valore specificato dall'opzione
max.
Opzioni
- minChars
Number Default: 1
The minimum number of characters a user has to type before the autocompleter activates.
- delay
Number Default: 400 for remote, 10 for local
The delay in milliseconds the autocompleter waits after a keystroke to activate itself.
- cacheLength
Number Default: 10
The number of backend query results to store in cache. If set to 1 (the current result), no
caching will happen. Must be >= 1.
- matchSubset
Boolean Default: true
Whether or not the autocompleter can use a cache for more specific queries. This means that all
matches of "foot" are a subset of all matches for "foo". Usually this is true, and using this
options decreases server load and increases performance. Only useful with cacheLength settings
bigger than one, like 10.
- matchCase
Boolean Default: false
Whether or not the comparison is case sensitive. Important only if you use caching.
- matchContains
Boolean Default: false
Whether or not the comparison looks inside (i.e. does "ba" match "foo bar") the search results.
Important only if you use caching. Don't mix with autofill.
- mustMatch
Boolean Default: false
If set to true, the autocompleter will only allow results that are presented by the backend.
Note that illegal values result in an empty input box.
- selectFirst
Boolean Default: true
If this is set to true, the first autocomplete value will be automatically selected on tab/return,
even if it has not been handpicked by keyboard or mouse action. If there is a handpicked (highlighted)
result, that result will take precedence.
- extraParams
Object
Extra parameters for the backend. If you were to specify { bar:4 }, the autocompleter would call
my_autocomplete_backend.php?q=foo&bar=4 (assuming the input box contains "foo"). The param can be
a function that is called to calculate the param before each request.
- formatItem
Function Default: Assumes that a single row contains a single value.
Provides advanced markup for an item. For each row of results, this function will be called.
The returned value will be displayed inside an LI element in the results list.
Autocompleter will provide 4 parameters: the results row, the position of the row in the list of
results (starting at 1), the number of items in the list of results and the search term.
- formatMatch
Function Default: formatItem is used
Use this option if you want to limit the data that autocomplete searches for matches. For example,
there may be items you want displayed to the user, but don't want included in the data that's searched.
Gets called with the same arguments as formatItem.
- formatResult
Function Default: Assumes either plain data to use as result or uses the same value as provided by formatItem.
Similar to formatItem, but provides the formatting for the value to be put into the input field.
Again three arguments: Data, position (starting with one) and total number of data.
- multiple
Boolean Default: false
Whether to allow more than one autocompleted-value to enter.
- multipleSeparator
String Default: ", "
Separator to put between values when using multiple option.
- width
Number Default: width of the input Element
Specify a custom width for the select box.
- autoFill
Boolean Default: false
Fill the textinput while still selecting a value, replacing the value if more is typed or
something else is selected.
- max
Number Default: 10
Limit the number of items in the select box. Is also sent as a "limit" parameter with a remote request.
- highlight
Boolean, Function Default: Wraps the search term in a <strong> Element
Whether and how to highlight matches in the select box. Set to false to disable.
Set to a function to customize. The function gets the value as the first argument and the search term
as the second and must return the formatted value.
- scroll
Boolean Default: true
Whether to scroll when more results than configured via scrollHeight are available.
- scrollHeight
Number Default: 180
height of scrolled autocomplete control in pixels
search()
Trigger a search event.
result(handler)
Arguments: handler Function The event handler, gets a default event object as first and the selected list item as second argument.
Handle the result of a search event. Is executed when the user selects a value or a programmatic
search event is triggered (see
search() ). You can add and remove (using unbind("result")) this event at any time.
$('input#suggest').result(function(event, data, formatted) {
$("#result").html( !data ? "No match!" : "Selected: " + formatted);
});
flushCache()
Flush (empty) the cache of matched input's autocompleters.
setOptions(options)
Updates the options for the current autocomplete field. This allows you to change things like the URL,
max items to display, etc. If you're changing the URL, be sure to call the flushCache() method.
$('input#suggest').setOptions({
max: 15
});