Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Page History: Quick Reference - jQuery

Compare Page Revisions



« Older Revision - Back to Page History - Newer Revision »


Page Revision: Tue, Mar 13, 2012, 1:13 PM


Table of Contents [Hide/Show]


   Online Repositories
      jQuery
      jQuery UI
   Field Values
      Text, Hidden, and Password Fields
      DropDownList
      CheckBox
      Radio Button
   Page Element Properties
      Enable/Disable
      Visiblility
   Selectors
      General
      Children
      Attributes
      Form Selectors
      Special Selectors
   AJAX Calls
      Client Code, AJAX
      Client Code, JSON
      Server Code
   Common Functions


Online Repositories

jQuery

  • https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js
  • http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js
  • http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

jQuery UI

  • https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js
  • http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js

Field Values

Text, Hidden, and Password Fields

Get Value$(selector).val()
Set Value$(selector).val('newValue')

DropDownList

Get Underlying Value$('select#id option:selected').val()
Get Displayed Text$('select#id option:selected').html()
Set Value$(selector).val('newValue')
Clear ValueNot applicable. An HTML dropdown always has a value selected.

NOTE: When setting the value of a drop down list, and the value doesn't exist, the behavior is browser-dependent.
  • IE simply leaves the dropdown selection unchanged.
  • FF and Chrome revert to the first item in the list.

CheckBox

Get Value$(selector).is(':checked')
Set Value$(selector).attr('checked', 'checked')
Clear Value$(selector).removeAttr('checked')

Radio Button

Get Value$('input:checked[name=MyName]).val() OR $(selector).is(':checked')
Set Value$('input[name=MyName]').filter('[value=MyValue]').attr('checked', 'checked');
Clear Value$('input[name=MyName]').removeAttr('checked');

Page Element Properties

Enable/Disable

Get Valuevar enabled = !$(selector).attr('disabled');
Set Enabled$(selector).removeAttr('disabled')
Set Disabled$(selector).attr('disabled','disabled')

Visiblility

Get Visibility$(selector).is(":visible")
Set Visible$(selector).show()
Set Invisible$(selector).hide()

Selectors

General

DescriptionExampleNotes
By tag name$('div')Selects all div tags in the document
By ID$('#myId')Selects the unique element with id='myId'
By Class$('.MyClass')Selects all elements with the class MyClass
Adjacent Sibling$('selectorE + selectorF')Selects all elements matching selectorF that immediately follow an element matching selectorE and have the same parent
$(selectorE).next('selectorF')
General Sibling$('selectorE ~ selectorF')Selects all elements matching selectorF that follow an element matching selectorE and have the same parent
Multiple Expressions$('selectorE, selectorF')Selects all elements matching selectorE or selectorF
Boolean NOT$(':not(selectorE)')Selects all elements not matching selectorE
Empty$(':empty')Selects all elements that have no children, including text nodes

Children

DescriptionExampleNotes
Descendant$('selectorE selectorF')Selects all elements matching selectorF that are descendants (to all levels) of an element matching selectorE
Children$('selectorE > selectorF')Selects all elements matching selectorF that are immediate children (to one level) of an element matching selectorE
Numbered child (Nth)$('li:nth-child(2)')Selects all li elements that are the second child of their parent
Numbered child (even/odd)$('tr:nth-child(odd)')Selects all tr elements that are the odd-numbered child of their parent
Numbered child (expression)$('.myclass:nth-child(3n+2)')Selects all elements with the class myclass that are the (3n+2)th child of their parent (i.e., 2nd, 5th, 8th, etc.)
First Child$('li:first-child')Selects all li elements that are the first child of their parent; the same as $('li:nth-child(1)')
Last Child$('li:last-child')Selects all li elements that are the last child of their parent
Only child$('li:only-child')Selects all li elements that are the only child of their parent

Attributes

DescriptionExampleNotes
Existence$('[rel]')Selects all elements that have the rel attribute, with any value
Equality$('[rel=value]')Selects all elements that have the rel attribute with the specified value
Inequality$('[rel!=value]')Selects all elements that do not have the rel attribute, or have it with a something other than the value specified
Starts With$('[rel^=value]')Selects all elements that have the rel attribute with a value starting with value
Ends With$('[rel$=value]')Selects all elements that have the rel attribute with a value ending with value
Contains$('[rel*=value]')Selects all elements that have the rel attribute with a value containing value
Contains Word$('[rel~=value]')Selects all elements that have the rel attribute with a value containing with word value (i.e., delimited by spaces)
Contains Prefix$('[rel|=value]')Selects all elements that have the rel attribute with a value either equal to value, or beginning with it and a hyphen

Form Selectors

DescriptionExampleNotes
Form element$(':input')Select all form elements: input (all types), select, textarea, button
Text fields$(':text')Selects all text fields: <input type='text'/>
Password fields$(':password')Selects all password fields: <input type='password'/>
Radio buttons$(':radio')Selects all radio buttons: <input type='radio'/>
Checkboxes$(':checkbox')Selects all checkboxes: <input type='checkbox'/>
Submit button$(':submit')Selects the submit button: <input type='submit'/>
Image button$(':image')Selects all image buttons: <input type='image'/>
Reset button$(':reset')Selects all reset buttons: <input type='reset'/>
Button$(':button')Selects all standard buttons: <input type='button'/>
File Upload$(':file')Selects all file uploads: <input type='file'/>
Enabled elements$(':enabled')Selects all elements that are enabled (i.e., that don't have a disabled attribute)
Disabled elements$(':disabled')Selects all elements that are disabled (i.e., that have a disabled attribute)
Checked Boxes$(':checked')Selects all elements (radio buttons and checkboxes) that are checked
Selected$(':selected')Selects all elements (i.e., option elements within a dropdown) that are selected

Special Selectors

DescriptionExampleNotes
Index Equality$(':eq(N)')Selects the element at index N (zero-based) within the matched set
Index Greater Than$(':gt(N)')Selects the element with an index (zero-based) greater than N within the matched set
Index Less Than$(':lt(N)')Selects the element with an index (zero-based) less than N within the matched set
First$(':first')Selects the first element within the matched set
Last$(':last')Selects the last element within the matched set
Even Elements$(':even')Selects the even-numbered (zero-based) element within the matched set
Odd Elements$(':odd')Selects the odd-numbered (zero-based) element within the matched set
Is Parent$(':parent')Selects all elements that are the parent of another, including text nodes
Contains Text$(':contains(value)')Selects all elements that contain value, either directly or within any descendant, or any combination thereof
Contains Element$(':has(selectorE)')Selects all elements that contain (at any level) an element matching selectorE
Visible$(':visible')Selects all visible elements
Hidden$(':hidden')Selects all hidden elements
Header Element$(':header')Selects all elements that are headers, such as <h1> or <h2>
Animation$(':animated')Selects all elements that are in the progress of an animation at the time the selector is run

AJAX Calls

Client Code, AJAX

$.ajax({
    type: "{ GET | POST }",
    url: "/Controller/Method",
    async: { false | true },
    datatype: 'json',
    data: { param1: value1, param2: value2 },
    success: function(data) {
        $.each(data, function(key, val) {
            // do something with each value
            }); /* each */
        }, /* success */
    error: function(xhr, ajaxOptions, statusDescription) {
        alert(statusDescription);
        } /* error */
}); /* ajax */

With the exception of the async parameter, the most common parameters can be remembered via the mnemonic device "dusted".
  • D = data
  • U = url
  • S = success
  • T = type
  • E = error
  • D = datatype

Notes
  • To trip the error function from server code, set the Response.StatusCode to 500, which indicates an internal server error, and DO NOT throw an exception.
  • Within the error function, the statusDescription parameter corresponds to the Response.StatusDescription value you set in your ASP.NET server code
  • Consider using the following server (controller) code to trap and bubble exceptions to the client code.

[HttpPost]
public JsonResult MyMethod(MyModel m)
{
    if (!ModelState.IsValid)
    {
        var response = (from ms in ModelState.Values
                        from err in ms.Errors
                        select err.ErrorMessage).ToList().FirstOrDefault();

        Response.StatusCode = 500;
        Response.StatusDescription = response;
        //return Json(response);
        return null;
    }

    m.SaveToDatabase()
    return Json("");

} 

Client Code, JSON


$.getJSON(
    url,
    { param1: value1, param2: value2 }, // optional
    function (data) {
        }
    )
    // optional success method
    .success(function(){
        })
    // optional error handler
    .error(function(){
        }); 


Server Code

[HttpGet, Authorize]
public JsonResult GetData(int regionID)
{
    IQueryable items = MyDataProvider.GetData(regionID);
    return Json(items, JsonRequestBehavior.AllowGet);
}

Common Functions

All of these can be performed on a the result of a query, e.g., $(selector).append(content).

FunctionDescription
.append(content)Inserts content at the end of the interior of the elements matched by the selector
.children(selector)Gets the child nodes matching the (optional) selector
.closest(selector)Gets the nearest ancestor matching the selector. Especially useful with the 'form' selector.
.eq(index)Select by index
.filter(selector)Further drill-down the selection of element(s)
.find(selector)Gets the descendants matching the selector
.first()Get just the first element in the set
.hasClass(class)Determine whether any of the matched elements are assigned the specified class.
.html()Returns all the inner HTML (i.e., not including the HTML for the element itself) within the selected elements
.last()Gets just the last element in the set
.next(selector)Gets the immediately next sibling to each element in the set, optionally filtered by a selector
.parent(selector)Gets the parent to each element in the set, optionally filtered by a selector
.prepend(content)Inserts content at the beginning the interior of the elements matched by the selector
.prev(selector)Gets the immediately previous sibling to each element in the set, optionally filtered by a selector
.replaceWith(content)Replaces the elements matched by the selector with the content
.toggle()Toggles the visibility of elements matched by the selector

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2024, Patrick Jasinski.