Section 11.3. Controls

11.3. Controls

The controls functionality (provided by controls.js and slider.js) provides JavaScript and Ajax-enhanced UI elements, namely auto-completing forms, in-place editors, and sliders.

11.3.1. Auto-Completion

Auto-completing fields come in two flavors: Autocompleter.Local (in which the auto-complete values are pre-loaded in JavaScript) and Ajax.Autocompleter (in which the auto-complete values are fetched dynamically via Ajax). Both classes extend Autocompleter.Base, an abstract class handling auto-completion independently of the data source for results.

CSS is used to control the appearance of auto-complete results. The suggested baseline rules look like this:

div.auto_complete       { width: 350px; background: #fff; } div.auto_complete ul    { border:1px solid #888; margin:0;                           padding:0; width:100%; list-style-type:none; } div.auto_complete ul li               { margin:0; padding:3px; } div.auto_complete ul li.selected      { background-color: #ffb; } div.auto_complete ul strong.highlight { color: #800; margin:0; padding:0; } Standard options

These options are available with both Autocompleter.Local and Ajax.Autocompleter.


Name of the parameter for the string typed by the user on the autocompletion field. Defaults to the name of the element.

Enables multiple values to be entered into an auto-complete field. For example, setting tokens to a comma (,) will enable multiple values to be entered, separated by commas. The tokens option may also be an array of choices (e.g., [',', '\n']), which enables auto-completion on multiple tokens. Defaults to [].

Determines the poll interval for auto-completion, in seconds. Defaults to 0.4.

Determines the minimum number of characters that must be present in the auto-complete field before results will be displayed. Defaults to 1.

Specifies an element that will be shown when auto-complete results are being retrieved and hidden when complete. Typically used with an animated "spinner" image. Defaults to null.

A callback function invoked after the element has been updated (i.e., when the user has selected an entry), instead of the built-in function that adds the list item text to the input field. The function receives one parameter only, the selected item (the <li> item selected from the auto-complete results). Defaults to null.

A callback function invoked after the element has been updated, after updateElement. Receives two parameters, the auto-completion input field and the selected item. Defaults to null. Local auto-completing

The Autocompleter.Local class is the local array auto-completer. It's used when you'd prefer to inject an array of auto-completion options into the page, rather than sending out Ajax queries. It's appropriate when the possible result set is relatively small and can be pre-loaded with the page.

initialize( element, update, array, options )

Constructor enabling auto-completion for the element textbox, creating an auto-completion menu in update based on the choices specified in array.

In addition to the options provided by Autocompleter.Base, options can contain these keys:


How many auto-completion choices to offer.

If false, the auto-completer will match entered text only at the beginning of strings in the auto-complete array. Defaults to true, which will match text at the beginning of any word in the strings in the autocomplete array. If you want to search anywhere in the string, additionally set the option fullSearch to true (default: off).

Search anywhere in auto-complete array strings.

How many characters to enter before triggering a partial match (unlike minChars, which defines how many characters are required to do any match at all). Defaults to 2.

Whether to ignore case when auto-completing. Defaults to true.

A function to implement custom auto-completion logic. In that case, the other options above will not apply unless you support them. Example

The simplest use of Autocompleter.Local consists of a regular form field, a DIV to hold the auto-complete results, and a JavaScript statement creating the Autocompleter.Local instance.

// <input type="text"  name="state" /> // <div  ></div> new Autocompleter.Local('state', 'state_results',   ['kansas', 'missouri', 'california', 'colorado', 'oklahoma',    'virginia', 'texas', 'georgia', 'tennessee', 'minnesota', 'illinois',    'iowa', 'nebraska', 'arkansas', 'florida', 'wyoming', 'indiana',    'south dakota', 'new york', 'vermont', 'west virginia', 'utah',    'maryland', 'mississippi', 'montana', 'washington', 'nevada',    'north dakota', 'arizona', 'alaska', 'hawaii', 'wisconsin', 'michigan',    'ohio', 'new hampshire', 'maine', 'rhode island', 'kentucky',    'north carolina', 'south carolina', 'alabama', 'louisiana',    'delaware', 'connecticut', 'oregon', 'pennsylvania']); Ajax auto-completion

The Ajax.Autocompleter class provides auto-completion functionality using Ajax, so auto-complete results are retrieved from the server. It's appropriate when the possible results set is too large to be loaded up front.

initialize( element, update, url, options )

Creates a new Ajax.Autocompleter instance. element is the text field to be given auto-complete capabilities. update is the element that holds the auto-complete results. url is the URL for the request that will return results.

In addition to the options provided by Autocompleter.Base, options can contain these keys:


Specifies the mode used by the Ajax request. Defaults to true.

A callback to handle the Ajax Request response. Defaults to the onComplete( ) method defined in Ajax.Autocompleter.

The HTTP method used for the Ajax request. Defaults to post. Example

The simplest use of Ajax.Autocompleter consists of a regular form field, a DIV to hold the auto-complete results, and a JavaScript statement creating the Ajax.Autocompleter instance.

// <input type="text"  name="country"/> // <div  ></div> new Ajax.Autocompleter('country',                        'country_results',                        '/autocomplete')

In this example, every time the field is changed will create an Ajax request to the URL /autocomplete, passing a parameter country with the current value of the field. The response is expected to be an HTML snippet of the form <ul><li> item1 </li><li> item2 </li></ul>. In Rails, this controller action works just that wayit takes a :country parameter, matches it against Rails' internal array of countries, and returns the first 10 hits in an HTML snippet.

COUNTRIES = ActionView::Helpers::             FormOptionsHelper.const_get :COUNTRIES def autocomplete   matches = COUNTRIES.grep[:country],'i')   items = matches[0..10].map { |c| "<li>#{c}</li>" }   render :text => "<ul>#{items}</ul>" end

The options object is passed on to the Ajax.Request constructor, so using HTTP GET rather than POST for the lookup is as simple as adding a method option:

new Ajax.Autocompleter('country',                        'country_results',                        '/autocomplete',                        {method:'get'})

11.3.2. In-Place Editors

In-place editors dynamically create forms to edit page elements and alert the remote server to the change via Ajax. In-place editors can be created with either text fields (using Ajax.InPlaceEditor) or select boxes (with Ajax.InPlaceCollectionEditor).

Most of the functionality is implemented by the Ajax.InPlaceEditor class:

initialize( element, url, options )

Adds in-place editing capabilities to element, and sends the changed value to url.

The server-side component gets the new value as the parameter value (POST method) and should send the new value as the body of the response. Options

The options parameter may include:


Boolean determining whether a submit button is shown in edit mode. Defaults to true.

The text of the submit button that submits the changed value to the server. Defaults to ok.

Boolean determining whether a cancel link is shown in edit mode. Defaults to true.

The text of the link that cancels editing. Defaults to cancel.

The text shown while the text is sent to the server. Defaults to Saving....

The text shown during mouse-over of the editable text. Defaults to Click to edit.

The ID given to the form element. Defaults to the ID of the element to edit plus InPlaceForm.

ID of an element that acts as an external control used to enter edit mode. The external control will be hidden when entering edit mode and shown again when leaving edit mode. Defaults to null.

The row height of the input field (anything greater than 1 uses a multiline textarea for input). Defaults to 1.

Callback run on successful update with server, conforming to Function( transport , element ). By default, creates a Highlight effect on element.

Callback run if update failed with server, conforming to Function( transport ). Defaults to creating a JavaScript alert( ) dialog.

The number of columns the text area should span (works for both single-line or multiline). Defaults to null.

Synonym for cols when using single-line input. Defaults to null.

The highlight color used by onComplete. Defaults to #FFFF99.

The color the highlight fades to. Defaults to #FFFFFF.

CSS class added to the element while displaying "Saving..." (removed when server responds). Defaults to inplaceeditor-saving.

CSS class used for the in-place edit form. Defaults to inplaceeditor-form.

Causes the text to be loaded from the server from this URL before editing. Useful, for example, if the text data is formatted with textile. Defaults to null.

If the loadTextURL option is specified, this text is displayed while the text is being loaded from the server. Defaults to "Loading...".

A function conforming to Function( form , value ) that will get executed just before the request is sent to the server. Should return the parameters to be sent in the URL. Defaults to the serialized version of form.

Passed through to the options parameter of Prototype's Ajax classes when loading and saving text. Defaults to an empty object.

If true, causes the editor form to be submitted when the cursor is removed from the field. Defaults to false. Examples

Creating a basic, one-line editor:

// <h1 >Testing</h1> new Ajax.InPlaceEditor('title', '/update');

Creating a multiline editor:

// <p >Woe for my blind folly! // Lone in thy blood thou liest, from friends' help afar.<br/> // And I the wholly witless, the all unwary,<br/> // Forbore to watch thee. Where, where<br/> // Lieth the fatally named, intractable Ajax?</p> new Ajax.InPlaceEditor('verse', '/update', {rows:10,cols:60});

To change the name of the parameter used in the Ajax request, use the callback option:

new Ajax.InPlaceEditor('title', '/words/update', { callback:                        function(form, value) {                          return 'title=' + escape(value) }})

To create a collection editor, use the Ajax.InPlaceCollectionEditor constructor, which creates a select box in place of the usual text field, populated with the values in the collection option. For example:

//<p>Access: <span >Public</span></p> new Ajax.InPlaceCollectionEditor( 'access', '/words/update',        { collection:['Public','Private','Friends Only'],         cancelLink:false }); Instance methods

enterEditMode( event )

Manually puts an editor into edit mode.

var editor = new Ajax.InPlaceEditor('title', '/update'); editor.enterEditMode('click');

leaveEditMode( )

Manually leaves edit mode.

var editor = new Ajax.InPlaceEditor('title', '/update'); editor.enterEditMode('click'); editor.leaveEditMode(  );

dispose( )

Removes in-place editing functionality from the editor.

var editor = new Ajax.InPlaceEditor('title', '/update'); editor.dispose(  );

11.3.3. Sliders

Defined in slider.js, which is not included by default in the Rails skeleton. The Control.Slider class creates slider widgets, enabling the user to choose a value along a range.

initialize( handle, track[, options] )

Constructor for a new slider object, enabling handle to slide along track. For example:

// .track { width:200px; background-color:#aaa; height:5px; } // .track div { width:5px; height:10px; background-color:#f00; cursor:move; } // <div  ><div ></div></div> new Control.Slider('handle', 'track');

If handle is an array, handles will be created from each element. The options object may have the following properties:


Specifies the slider's directionhorizontal (default) or vertical.

Determines the minimum and maximum value for the slider, specified as a Range object (see "Ranges " in Chapter 10). Defaults to $R(0,1).

An array of possible values for the slider. Defaults to null.

Sets the initial slider value. If an array, sets the initial values for each handle.

A callback function conforming to Function( value , slider ) called while a handle is slid. If the slider has multiple handles, the first argument is an array of values. Defaults to null.

A callback function conforming to Function( value , slider ) called when a handle has finished. If the slider has multiple handles, the first argument is an array of values. Defaults to null.

An array of elements to be used as spans, stretching between handles. Defaults to null.

When using multiple handles, determines whether a handle is allowed to pass an adjacent handle. Defaults to false.

Overrides the maximum set by the range option.

Overrides the minimum set by the range option.

Used to offset the horizontal position of the handle. Defaults to 0.

Used to offset the vertical position of the handle. Defaults to 0.

If true, the slider will not move. Defaults to false. Examples

Use the following CSS rules for these examples to display reasonably:

.track { width:200px; background-color:#aaa;             height:5px; position:relative; } .track.vertical { height:100px; width:5px; } .handle { width:5px; height:10px; background-color:#f00;             cursor:move; position:absolute; } .track.vertical .handle { width:10px; height:5px; } .span { position: absolute; background-color: #faf;         z-index:-1; height: 10px; }

Creating a slider that updates an element with its value:

// <div  > //   <div  ></div> // </div> // <div ></div> new Control.Slider('handle', 'track', {   onSlide:function(v){$('debug').innerHTML='slide: '+v},   onChange:function(v){$('debug').innerHTML='changed! '+v}});

Creating a vertical slider:

// <div  > //   <div  ></div> // </div> new Control.Slider('handle', 'track', { axis:'vertical' });

Specifying custom range and values:

// <div  > //   <div  ></div> // </div> new Control.Slider('handle', 'track', {   range:$R(0,200),   values:[0,50,100,150,200] });

Adjusting the size of another element in proportion with the slider:

// <div  > //   <div  ></div> // </div> // <div   style="width:1px"></div> new Control.Slider('handle', 'track', {   range:$R(0,20),   values:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],   onSlide:function(v){ $('bar').style.width=(v*3)+'px'; }});

Creating multiple handles and setting default slider values:

// <div  > //   <div  ></div> //   <div  ></div> // </div> new Control.Slider(['handle1', 'handle2'], 'track', {   sliderValue:[ 0.25, 0.5 ]});

Sending an Ajax notification to the server when the slider value changes:

new Control.Slider('handle', 'track', {   onChange:function(value){     new Ajax.Request('/update', { parameters:'value=' + value });   }});

Creating a span element between two handles:

// <div  > //   <div  ></div> //   <div  ></div> //   <div  ></div> // </div> new Control.Slider(['handle1','handle2'], 'track', {   sliderValue:[0.2, 0.8],   spans:['span'] });

Creating external controls for a slider:

var slider = new Control.Slider('handle', 'track'); // <a href="#" onclick="slider.setValueBy(-0.1);return false;">down</a> // <a href="#" onclick="slider.setValueBy(0.1);return false;">up</a> Instance methods

setDisabled( )

Disables the slider.

var slider = new Control.Slider('handle', 'track'); slider.setDisabled(  );

setEnabled( )

Enables the slider.

var slider = new Control.Slider('handle', 'track'); slider.setDisabled(  ); slider.setEnabled(  );

setValue( setValue[, handleIdx] )

Sets the value of the slider, moving the handle accordingly. If the slider has multiple handles and handleIdx is specified, sets the value of the corresponding handle, according to the order created.

var slider = new Control.Slider('handle', 'track'); slider.setValue(0.5);

setValueBy( delta, handleIdx )

Changes the value of the slider by delta. If the slider has multiple handles and handleIdx is specified, changes the value of the corresponding handle, according to the order created.

var slider = new Control.Slider('handle', 'track',); // starts at 0 slider.setValueBy(0.5); // now at 0.5 slider.setValueBy(0.25); // now at 0.75 slider.setValueBy(-0.5); // now at 0.25

dispose( )

Destroys the slider instance.

var slider = new Control.Slider('handle', 'track'); slider.dispose(  );

Ajax on Rails
Ajax on Rails
ISBN: 0596527446
EAN: 2147483647
Year: 2006
Pages: 103
Authors: Scott Raymond

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: