[jQuery] form validation

프로그래밍/Web 2011. 3. 2. 15:24 Posted by galad
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

간단하게 쓰기. class만 맞춰주면 OK.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>이미지 추가 생성 화면</title>

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/cms/make_new_image.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/cms/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/cms/jquery/jquery.validate.js"></script>

<script type="text/javascript">
$(document).ready(function(){
    $("#mainForm").validate();
});
</script>
</head>
<body>
<form action="" id="mainForm">
컨텐트 종류 <s:select name="contentType" list="contentTypeList" listValue="label" listKey="key"></s:select>
<br>
원본 메타 필드명 <s:textfield name="srcMeta" cssClass="required"></s:textfield>
<br>
대상 메타 필드명 <s:textfield name="destMeta" cssClass="required"></s:textfield>
<br>
리사이즈 크기 : 가로 <s:textfield name="width" cssClass="required number"></s:textfield> 세로 <s:textfield name="height" cssClass="required number"></s:textfield>
<br>
<s:submit></s:submit>
</form>
</body>
</html>


경고문구 css 설정하기
label.error {
    /* remove the next line when you have trouble in IE6 with labels in list */
    color: red;
    font-style: italic
}

그밖의 여러가지 사용법 - 나만의 유효성검사룰 설정하기, ajax 등은 예제 참고.

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.lang.StringUtils"%>
<%@ page import="com.omp.commons.utils.SessionUtil" %>
<%@ page import="com.omp.bp.cms.member.MemberConstants"%>
<%@ page import="com.omp.bp.cms.member.model.LoginUserInfo" %>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>이미지 추가 생성 화면</title>

<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/cms/make_new_image.css">
<script type="text/javascript" src="${pageContext.request.contextPath}/js/cms/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/cms/jquery/jquery.validate.js"></script>

<script type="text/javascript">
var m_browser;
var m_version;

function detectBrowser() {
    if($.browser.msie) {
        m_browser = "msie";
    }
    else if($.browser.safari) {
        m_browser = "safari";
    }
    else if($.browser.opera) {
        m_browser = "opera";
    }
    else if($.browser.mozilla) {
        m_browser = "mozilla";
    }

    m_version = $.browser.version;
    //alert(m_browser + " " + m_version);
}

$(document).ready(function(){
    detectBrowser(); // browser/version check

    // 폼 유효성 검사
    $("#mainForm").validate({
        submitHandler: function(form) {
            // do other stuff for a valid form
            disableSubmit();
            form.submit();
        }
    });

    /*$("#submitBtn").click(function(){ // 유효성 검사 통과했을 때만 실행하도록 수정
        disableSubmit();
    });*/

    parentResize(); // admin poc 화면 크기 조절용
});

function disableSubmit() {
    $("#submitBtn").hide();
    $("#submitLbl").show();
}

function parentResize() {
<%
    LoginUserInfo loginInfo = (LoginUserInfo)SessionUtil.getMemberSession(request);
    boolean isAdmin = StringUtils.equalsIgnoreCase(loginInfo.getMemberType(), MemberConstants.MEMBER_TYPE_ADMIN);
%>
    //운영자면 adminpoc의 프레임 크기 조절용 스크립트를 실행
    var isAdmin = <%=isAdmin%>;
    if(isAdmin) {
        rsize();
    }
}

function rsize() {
    var iframe = document.getElementById( 'inneriframe' );
    var height = Math.max( 200, document.body.scrollHeight + 500 );
    iframe.src = '<%=loginInfo.getAdminpocResizeUrl()%>?height='+height;
}
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/common/makeNewImage.omp" id="mainForm" method="post">
컨텐트 종류 <s:select name="contentType" list="contentTypeList" listValue="label" listKey="key"></s:select>
<br>
원본 메타 필드명 <s:textfield name="srcMeta" cssClass="required"></s:textfield>
<br>
대상 메타 필드명 <s:textfield name="destMeta" cssClass="required"></s:textfield>
<br>
리사이즈 크기 : 가로 <s:textfield name="width" cssClass="required number"></s:textfield> 세로 <s:textfield name="height" cssClass="required number"></s:textfield>
<br>
<s:submit id="submitBtn" value="이미지 생성 시작"></s:submit><label id="submitLbl" style="display: none;">이미지 생성 처리중...</label>
</form>
</body>
</html>



'프로그래밍 > Web' 카테고리의 다른 글

[jsp] include  (0) 2011.05.25
[jsp/servlet] jsp 와 servlet 의 차이  (0) 2010.10.29
[펌] jQuery Fundamentals  (1) 2010.10.07
[html] 웹페이지에서 마우스 툴팁(Tooltip; 말풍선) 태그(Tag)  (0) 2010.05.31
[script] 정규식  (0) 2010.05.20

[펌] jQuery Fundamentals

프로그래밍/Web 2010. 10. 7. 10:46 Posted by galad
http://jqfundamentals.com/book/book.html

아래의 내용은 위의 링크의 내용을 그대로 복사한 것입니다.
단지 보존의 목적으로만 사용함을 밝힙니다.

With contributions by James Padolsey, Paul Irish, and others. See the GitHub repository for a complete history of contributions.

Licensed by Rebecca Murphey under the Creative Commons Attribution-Share Alike 3.0 United States license. You are free to copy, distribute, transmit, and remix this work, provided you attribute the work to Rebecca Murphey as the original author and reference the GitHub repository for the work. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. Any of the above conditions can be waived if you get permission from the copyright holder. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to the license.


Table of Contents

1. Welcome
Getting the Code
Software
Adding JavaScript to Your Page
JavaScript Debugging
Exercises
Conventions used in this book
Reference Material
I. JavaScript 101
2. JavaScript Basics
Overview
Syntax Basics
Operators
Basic Operators
Operations on Numbers & Strings
Logical Operators
Comparison Operators
Conditional Code
Truthy and Falsy Things
Conditional Variable Assignment with The Ternary Operator
Switch Statements
Loops
The for loop
The while loop
The do-while loop
Breaking and continuing
Reserved Words
Arrays
Objects
Functions
Using Functions
Self-Executing Anonymous Functions
Functions as Arguments
Testing Type
Scope
Closures
II. jQuery: Basic Concepts
3. jQuery Basics
$(document).ready()
Selecting Elements
Does My Selection Contain Any Elements?
Saving Selections
Refining & Filtering Selections
Selecting Form Elements
Working with Selections
Chaining
Getters & Setters
CSS, Styling, & Dimensions
Using CSS Classes for Styling
Dimensions
Attributes
Traversing
Manipulating Elements
Getting and Setting Information about Elements
Moving, Copying, and Removing Elements
Creating New Elements
Manipulating Attributes
Exercises
Selecting
Traversing
Manipulating
4. jQuery Core
$ vs $()
Utility Methods
Checking types
Data Methods
Feature & Browser Detection
Avoiding Conflicts with Other Libraries
5. Events
Overview
Connecting Events to Elements
Connecting Events to Run Only Once
Disconnecting Events
Namespacing Events
Inside the Event Handling Function
Triggering Event Handlers
Increasing Performance with Event Delegation
Unbinding Delegated Events
Event Helpers
$.fn.hover
$.fn.toggle
Exercises
Create an Input Hint
Add Tabbed Navigation
6. Effects
Overview
Built-in Effects
Changing the Duration of Built-in Effects
Doing Something when an Effect is Done
Custom Effects with $.fn.animate
Easing
Managing Effects
Exercises
Reveal Hidden Text
Create Dropdown Menus
Create a Slideshow
7. Ajax
Overview
Key Concepts
GET vs. Post
Data Types
A is for Asynchronous
Same-Origin Policy and JSONP
Ajax and Firebug
jQuery's Ajax-Related Methods
$.ajax
Convenience Methods
$.fn.load
Ajax and Forms
Working with JSONP
Ajax Events
Exercises
Load External Content
Load Content Using JSON
8. Plugins
What exactly is a plugin?
How to create a basic plugin
Finding & Evaluating Plugins
Writing Plugins
Writing Stateful Plugins with the jQuery UI Widget Factory
Adding Methods to a Widget
Working with Widget Options
Adding Callbacks
Cleaning Up
Conclusion
Exercises
Make a Table Sortable
Write a Table-Striping Plugin
III. Advanced Topics
This Section is a Work in Progress
9. Performance Best Practices
Cache length during loops
Append new content outside of a loop
Keep things DRY
Beware anonymous functions
Optimize Selectors
ID-Based Selectors
Specificity
Avoid the Universal Selector
Use Event Delegation
Detach Elements to Work With Them
Use Stylesheets for Changing CSS on Many Elements
Use $.data Instead of $.fn.data
Don't Act on Absent Elements
Variable Definition
Conditionals
Don't Treat jQuery as a Black Box
10. Code Organization
Overview
Key Concepts
Encapsulation
The Object Literal
The Module Pattern
Managing Dependencies
Getting RequireJS
Using RequireJS with jQuery
Creating Reusable Modules with RequireJS
Optimizing Your Code: The RequireJS Build Tool
Exercises
Create a Portlet Module
11. Custom Events
Introducing Custom Events
A Sample Application

List of Examples

1.1. An example of inline Javascript
1.2. An example of including external JavaScript
1.3. Example of an example
2.1. A simple variable declaration
2.2. Whitespace has no meaning outside of quotation marks
2.3. Parentheses indicate precedence
2.4. Tabs enhance readability, but have no special meaning
2.5. Concatenation
2.6. Multiplication and division
2.7. Incrementing and decrementing
2.8. Addition vs. concatenation
2.9. Forcing a string to act as a number
2.10. Forcing a string to act as a number (using the unary-plus operator)
2.11. Logical AND and OR operators
2.12. Comparison operators
2.13. Flow control
2.14. Values that evaluate to true
2.15. Values that evaluate to false
2.16. The ternary operator
2.17. A switch statement
2.18. Loops
2.19. A typical for loop
2.20. A typical while loop
2.21. A while loop with a combined conditional and incrementer
2.22. A do-while loop
2.23. Stopping a loop
2.24. Skipping to the next iteration of a loop
2.25. A simple array
2.26. Accessing array items by index
2.27. Testing the size of an array
2.28. Changing the value of an array item
2.29. Adding elements to an array
2.30. Working with arrays
2.31. Creating an "object literal"
2.32. Function Declaration
2.33. Named Function Expression
2.34. A simple function
2.35. A function that returns a value
2.36. A function that returns another function
2.37. A self-executing anonymous function
2.38. Passing an anonymous function as an argument
2.39. Passing a named function as an argument
2.40. Testing the type of various variables
2.41. Functions have access to variables defined in the same scope
2.42. Code outside the scope in which a variable was defined does not have access to the variable
2.43. Variables with the same name can exist in different scopes with different values
2.44. Functions can "see" changes in variable values after the function is defined
2.45. Scope insanity
2.46. How to lock in the value of i?
2.47. Locking in the value of i with a closure
3.1. A $(document).ready() block
3.2. Shorthand for $(document).ready()
3.3. Passing a named function instead of an anonymous function
3.4. Selecting elements by ID
3.5. Selecting elements by class name
3.6. Selecting elements by attribute
3.7. Selecting elements by compound CSS selector
3.8. Pseudo-selectors
3.9. Testing whether a selection contains elements
3.10. Storing selections in a variable
3.11. Refining selections
3.12. Using form-related pseduo-selectors
3.13. Chaining
3.14. Formatting chained code
3.15. Restoring your original selection using $.fn.end
3.16. The $.fn.html method used as a setter
3.17. The html method used as a getter
3.18. Getting CSS properties
3.19. Setting CSS properties
3.20. Working with classes
3.21. Basic dimensions methods
3.22. Setting attributes
3.23. Getting attributes
3.24. Moving around the DOM using traversal methods
3.25. Iterating over a selection
3.26. Changing the HTML of an element
3.27. Moving elements using different approaches
3.28. Making a copy of an element
3.29. Creating new elements
3.30. Creating a new element with an attribute object
3.31. Getting a new element on to the page
3.32. Creating and adding an element to the page at the same time
3.33. Manipulating a single attribute
3.34. Manipulating multiple attributes
3.35. Using a function to determine an attribute's new value
4.1. Checking the type of an arbitrary value
4.2. Storing and retrieving data related to an element
4.3. Storing a relationship between elements using $.fn.data
4.4. Putting jQuery into no-conflict mode
4.5. Using the $ inside a self-executing anonymous function
5.1. Event binding using a convenience method
5.2. Event biding using the $.fn.bind method
5.3. Event binding using the $.fn.bind method with data
5.4. Switching handlers using the $.fn.one method
5.5. Unbinding all click handlers on a selection
5.6. Unbinding a particular click handler
5.7. Namespacing events
5.8. Preventing a link from being followed
5.9. Triggering an event handler the right way
5.10. Event delegation using $.fn.delegate
5.11. Event delegation using $.fn.live
5.12. Unbinding delegated events
5.13. The hover helper function
5.14. The toggle helper function
6.1. A basic use of a built-in effect
6.2. Setting the duration of an effect
6.3. Augmenting jQuery.fx.speeds with custom speed definitions
6.4. Running code when an animation is complete
6.5. Run a callback even if there were no elements to animate
6.6. Custom effects with $.fn.animate
6.7. Per-property easing
7.1. Using the core $.ajax method
7.2. Using jQuery's Ajax convenience methods
7.3. Using $.fn.load to populate an element
7.4. Using $.fn.load to populate an element based on a selector
7.5. Turning form data into a query string
7.6. Creating an array of objects containing form data
7.7. Using YQL and JSONP
7.8. Setting up a loading indicator using Ajax Events
8.1. Creating a plugin to add and remove a class on hover
8.2. The Mike Alsup jQuery Plugin Development Pattern
8.3. A simple, stateful plugin using the jQuery UI widget factory
8.4. Passing options to a widget
8.5. Setting default options for a widget
8.6. Creating widget methods
8.7. Calling methods on a plugin instance
8.8. Responding when an option is set
8.9. Providing callbacks for user extension
8.10. Binding to widget events
8.11. Adding a destroy method to a widget
10.1. An object literal
10.2. Using an object literal for a jQuery feature
10.3. The module pattern
10.4. Using the module pattern for a jQuery feature
10.5. Using RequireJS: A simple example
10.6. A simple JavaScript file with dependencies
10.7. Defining a RequireJS module that has no dependencies
10.8. Defining a RequireJS module with dependencies
10.9. Defining a RequireJS module that returns a function
10.10. A RequireJS build configuration file

jQuery is fast becoming a must-have skill for front-end developers. The purpose of this book is to provide an overview of the jQuery JavaScript library; when you're done with the book, you should be able to complete basic tasks using jQuery, and have a solid basis from which to continue your learning. This book was designed as material to be used in a classroom setting, but you may find it useful for individual study.

This is a hands-on class. We will spend a bit of time covering a concept, and then you’ll have the chance to work on an exercise related to the concept. Some of the exercises may seem trivial; others may be downright daunting. In either case, there is no grade; the goal is simply to get you comfortable working your way through problems you’ll commonly be called upon to solve using jQuery. Example solutions to all of the exercises are included in the sample code.

The code we’ll be using in this book is hosted in a repository on Github. You can download a .zip or .tar file of the code, then uncompress it to use it on your server. If you’re git-inclined, you’re welcome to clone or fork the repository.

Logical operators allow you to evaluate a series of operands using AND and OR operations.


Though it may not be clear from the example, the || operator returns the value of the first truthy operand, or, in cases where neither operand is truthy, it'll return the last of both operands. The &&operator returns the value of the first false operand, or the value of the last operand if both operands are truthy.

Be sure to consult the section called “Truthy and Falsy Things” for more details on which values evaluate to true and which evaluate to false.

Note

You'll sometimes see developers use these logical operators for flow control instead of using if statements. For example:

// do something with foo if foo is truthy
foo && doSomething(foo);

// set bar to baz if baz is truthy;
// otherwise, set it to the return
// value of createBar()
var bar = baz || createBar();

This style is quite elegant and pleasantly terse; that said, it can be really hard to read, especially for beginners. I bring it up here so you'll recognize it in code you read, but I don't recommend using it until you're extremely comfortable with what it means and how you can expect it to behave.

Sometimes you only want to run a block of code under certain conditions. Flow control — via if andelse blocks — lets you run code only under certain conditions.


Note

While curly braces aren't strictly required around single-line if statements, using them consistently, even when they aren't strictly required, makes for vastly more readable code.

Be mindful not to define functions with the same name multiple times within separate if/elseblocks, as doing so may not have the expected result.

Loops let you run a block of code a certain number of times.


Note that in 
Example 2.18, “Loops” even though we use the keyword var before the variable namei, this does not "scope" the variable i to the loop block. We'll discuss scope in depth later in this chapter.

Functions contain blocks of code that need to be executed repeatedly. Functions can take zero or more arguments, and can optionally return a value.

Functions can be created in a variety of ways:



I prefer the named function expression method of setting a function's name, for some rather in-depth and technical reasons. You are likely to see both methods used in others' JavaScript code.

"Scope" refers to the variables that are available to a piece of code at a given time. A lack of understanding of scope can lead to frustrating debugging experiences.

When a variable is declared inside of a function using the var keyword, it is only available to code inside of that function -- code outside of that function cannot access the variable. On the other hand, functions defined inside that function will have access to to the declared variable.

Furthermore, variables that are declared inside a function without the var keyword are not local to the function -- JavaScript will traverse the scope chain all the way up to the window scope to find where the variable was previously defined. If the variable wasn't previously defined, it will be defined in the global scope, which can have extremely unexpected consequences;






The most basic concept of jQuery is to “select some elements and do something with them.” jQuery supports most CSS3 selectors, as well as some non-standard selectors. For a complete selector reference, visit http://api.jquery.com/category/selectors/.

Following are a few examples of common selection techniques.






Note

When you use the :visible and :hidden pseudo-selectors, jQuery tests the actual visibility of the element, not its CSS visibility or display — that is, it looks to see if the element's physical height and width on the page are both greater than zero. However, this test doesn't work with <tr> elements; in this case, jQuery does check the CSS display property, and considers an element hidden if its display property is set to none. Elements that have not been added to the DOM will always be considered hidden, even if the CSS that would affect them would render them visible. (See the Manipulation section later in this chapter to learn how to create and add elements to the DOM.)

For reference, here is the code jQuery uses to determine whether an element is visible or hidden, with comments added for clarity:

jQuery.expr.filters.hidden = function( elem ) {
    var width = elem.offsetWidth, height = elem.offsetHeight,
        skip = elem.nodeName.toLowerCase() === "tr";

    // does the element have 0 height, 0 width, 
    // and it's not a <tr>?
    return width === 0 && height === 0 && !skip ?

        // then it must be hidden
        true :

        // but if it has width and height 
        // and it's not a <tr>
        width > 0 && height > 0 && !skip ?

            // then it must be visible
            false :

            // if we get here, the element has width
            // and height, but it's also a <tr>,
            // so check its display property to
            // decide whether it's hidden
            jQuery.curCSS(elem, "display") === "none";
};

jQuery.expr.filters.visible = function( elem ) {
    return !jQuery.expr.filters.hidden( elem );
};

Every time you make a selection, a lot of code runs, and jQuery doesn't do caching of selections for you. If you've made a selection that you might need to make again, you should save the selection in a variable rather than making the selection repeatedly.


Note

In Example 3.10, “Storing selections in a variable”, the variable name begins with a dollar sign. Unlike in other languages, there's nothing special about the dollar sign in JavaScript -- it's just another character. We use it here to indicate that the variable contains a jQuery object. This practice -- a sort of Hungarian notation -- is merely convention, and is not mandatory.

Once you've stored your selection, you can call jQuery methods on the variable you stored it in just like you would have called them on the original selection.

Note

A selection only fetches the elements that are on the page when you make the selection. If you add elements to the page later, you'll have to repeat the selection or otherwise add them to the selection stored in the variable. Stored selections don't magically update when the DOM changes.

Once you have a selection, you can call methods on the selection. Methods generally come in two different flavors: getters and setters. Getters return a property of the first selected element; setters set a property on all selected elements.

jQuery includes a handy way to get and set CSS properties of elements.

Note

CSS properties that normally include a hyphen need to be camel cased in JavaScript. For example, the CSS property font-size is expressed asfontSize in JavaScript.



Note the style of the argument we use on the second line -- it is an object that contains multiple properties. This is a common way to pass multiple arguments to a function, and many jQuery setter methods accept objects to set mulitple values at once.

Once you've made a selection, the fun begins. You can change, move, remove, and clone elements. You can also create new elements via a simple syntax.

For complete documentation of jQuery manipulation methods, visithttp://api.jquery.com/category/manipulation/.

There are any number of ways you can change an existing element. Among the most common tasks you'll perform is changing the inner HTML or attribute of an element. jQuery offers simple, cross-browser methods for these sorts of manipulations. You can also get information about elements using many of the same methods in their getter incarnations. We'll see examples of these throughout this section, but specifically, here are a few methods you can use to get and set information about elements.

Note

Changing things about elements is trivial, but remember that the change will affect all elements in the selection, so if you just want to change one element, be sure to specify that in your selection before calling a setter method.

Note

When methods act as getters, they generally only work on the first element in the selection, and they do not return a jQuery object, so you can't chain additional methods to them. One notable exception is $.fn.text; as mentioned below, it gets the text for all elements in the selection.

$.fn.html

Get or set the html contents.

$.fn.text

Get or set the text contents; HTML will be stripped.

$.fn.attr

Get or set the value of the provided attribute.

$.fn.width

Get or set the width in pixels of the first element in the selection as an integer.

$.fn.height

Get or set the height in pixels of the first element in the selection as an integer.

$.fn.position

Get an object with position information for the first element in the selection, relative to its first positioned ancestor. This is a getter only.

$.fn.val

Get or set the value of form elements.


There are a variety of ways to move elements around the DOM; generally, there are two approaches:

  • Place the selected element(s) relative to another element

  • Place an element relative to the selected element(s)

For example, jQuery provides $.fn.insertAfter and $.fn.after. The $.fn.insertAftermethod places the selected element(s) after the element that you provide as an argument; the$.fn.after method places the element provided as an argument after the selected element. Several other methods follow this pattern: $.fn.insertBefore and $.fn.before;$.fn.appendTo and $.fn.append; and $.fn.prependTo and $.fn.prepend.

The method that makes the most sense for you will depend on what elements you already have selected, and whether you will need to store a reference to the elements you're adding to the page. If you need to store a reference, you will always want to take the first approach -- placing the selected elements relative to another element -- as it returns the element(s) you're placing. In this case,$.fn.insertAfter, $.fn.insertBefore, $.fn.appendTo, and $.fn.prependTo will be your tools of choice.


jQuery offers a trivial and elegant way to create new elements using the same $() method you use to make selections.



Note that in the attributes object we included as the second argument, the property name class is quoted, while the property names text and href are not. Property names generally do not need to be quoted unless they are reserved words (as class is in this case).

When you create a new element, it is not immediately added to the page. There are several ways to add an element to the page once it's been created.


Strictly speaking, you don't have to store the created element in a variable -- you could just call the method to add the element to the page directly after the $(). However, most of the time you will want a reference to the element you added, so you don't need to select it later.

You can even create an element as you're adding it to the page, but note that in this case you don't get a reference to the newly created element.


Note

The syntax for adding new elements to the page is so easy, it's tempting to forget that there's a huge performance cost for adding to the DOM repeatedly. If you are adding many elements to the same container, you'll want to concatenate all the html into a single string, and then append that string to the container instead of appending the elements one at a time. You can use an array to gather all the pieces together, then join them into a single string for appending.

var myItems = [], $myList = $('#myList');

for (var i=0; i<100; i++) {
    myItems.push('<li>item ' + i + '</li>');
}

$myList.append(myItems.join(''));

jQuery offers several utility methods in the $ namespace. These methods are helpful for accomplishing routine programming tasks. Below are examples of a few of the utility methods; for a complete reference on jQuery utility methods, visit http://api.jquery.com/category/utilities/.

$.trim

Removes leading and trailing whitespace.

$.trim('    lots of extra whitespace    ');
// returns 'lots of extra whitespace'
$.each

Iterates over arrays and objects.

$.each([ 'foo', 'bar', 'baz' ], function(idx, val) {
    console.log('element ' + idx + 'is ' + val);
});

$.each({ foo : 'bar', baz : 'bim' }, function(k, v) {
    console.log(k + ' : ' + v);
});

Note

There is also a method $.fn.each, which is used for iterating over a selection of elements.

$.inArray

Returns a value's index in an array, or -1 if the value is not in the array.

var myArray = [ 1, 2, 3, 5 ];

if ($.inArray(4, myArray) !== -1) {
    console.log('found it!');
}
$.extend

Changes the properties of the first object using the properties of subsequent objects.

var firstObject = { foo : 'bar', a : 'b' };
var secondObject = { foo : 'baz' };

var newObject = $.extend(firstObject, secondObject);
console.log(firstObject.foo); // 'baz'
console.log(newObject.foo);   // 'baz'

If you don't want to change any of the objects you pass to $.extend, pass an empty object as the first argument.

var firstObject = { foo : 'bar', a : 'b' };
var secondObject = { foo : 'baz' };

var newObject = $.extend({}, firstObject, secondObject);
console.log(firstObject.foo); // 'bar'
console.log(newObject.foo);   // 'baz'
$.proxy

Returns a function that will always run in the provided scope — that is, sets the meaning of thisinside the passed function to the second argument.

var myFunction = function() { console.log(this); };
var myObject = { foo : 'bar' };

myFunction(); // logs window object

var myProxyFunction = $.proxy(myFunction, myObject);
myProxyFunction(); // logs myObject object

If you have an object with methods, you can pass the object and the name of a method to return a function that will always run in the scope of the object.

var myObject = {
    myFn : function() {
        console.log(this);
    }
};

$('#foo').click(myObject.myFn); // logs DOM element #foo
$('#foo').click($.proxy(myObject, 'myFn')); // logs myObject

As your work with jQuery progresses, you'll find that there's often data about an element that you want to store with the element. In plain JavaScript, you might do this by adding a property to the DOM element, but you'd have to deal with memory leaks in some browsers. jQuery offers a straightforward way to store data related to an element, and it manages the memory issues for you.


You can store any kind of data on an element, and it's hard to overstate the importance of this when you get into complex application development. For the purposes of this class, we'll mostly use$.fn.data to store references to other elements.

For example, we may want to establish a relationship between a list item and a div that's inside of it. We could establish this relationship every single time we interact with the list item, but a better solution would be to establish the relationship once, and then store a pointer to the div on the list item using $.fn.data:


In addition to passing $.fn.data a single key-value pair to store data, you can also pass an object containing one or more pairs.

Although jQuery eliminates most JavaScript browser quirks, there are still occasions when your code needs to know about the browser environment.

jQuery offers the $.support object, as well as the deprecated $.browser object, for this purpose. For complete documentation on these objects, visit http://api.jquery.com/jQuery.support/ andhttp://api.jquery.com/jQuery.browser/.

The $.support object is dedicated to determining what features a browser supports; it is recommended as a more “future-proof” method of customizing your JavaScript for different browser environments.

The $.browser object was deprecated in favor of the $.support object, but it will not be removed from jQuery anytime soon. It provides direct detection of the browser brand and version.

jQuery offers convenience methods for most common events, and these are the methods you will see used most often. These methods -- including $.fn.click, $.fn.focus, $.fn.blur,$.fn.change, etc. -- are shorthand for jQuery's $.fn.bind method. The bind method is useful for binding the same hadler function to multiple events, and is also used when you want to provide data to the event hander, or when you are working with custom events.




You'll frequently use jQuery to add new elements to the page, and when you do, you may need to bind events to those new elements -- events you already bound to similar elements that were on the page originally. Instead of repeating your event binding every time you add elements to the page, you can use event delegation. With event delegation, you bind your event to a container element, and then when the event occurs, you look to see which contained element it occurred on. If this sounds complicated, luckily jQuery makes it easy with its $.fn.live and $.fn.delegate methods.

While most people discover event delegation while dealing with elements added to the page later, it has some performance benefits even if you never add more elements to the page. The time required to bind event handlers to hundreds of individual elements is non-trivial; if you have a large set of elements, you should consider delegating related events to a container element.

Note

The $.fn.live method was introduced in jQuery 1.3, and at that time only certain event types were supported. As of jQuery 1.4.2, the $.fn.delegatemethod is available, and is the preferred method.



Frequently used effects are built into jQuery as methods:

$.fn.show

Show the selected element.

$.fn.hide

Hide the selected elements.

$.fn.fadeIn

Animate the opacity of the selected elements to 100%.

$.fn.fadeOut

Animate the opacity of the selected elements to 0%.

$.fn.slideDown

Display the selected elements with a vertical sliding motion.

$.fn.slideUp

Hide the selected elements with a vertical sliding motion.

$.fn.slideToggle

Show or hide the selected elements with a vertical sliding motion, depending on whether the elements are currently visible.


Proper use of Ajax-related jQuery methods requires understanding some key concepts first.

jQuery generally requires some instruction as to the type of data you expect to get back from an Ajax request; in some cases the data type is specified by the method name, and in other cases it is provided as part of a configuration object. There are several options:

text

For transporting simple strings

html

For transporting blocks of HTML to be placed on the page

script

For adding a new script to the page

json

For transporting JSON-formatted data, which can include strings, arrays, and objects

Note

As of jQuery 1.4, if the JSON data sent by your server isn't properly formatted, the request may fail silently. See http://json.org for details on properly formatting JSON, but as a general rule, use built-in language methods for generating JSON on the server to avoid syntax issues.

jsonp

For transporting JSON data from another domain

xml

For transporting data in a custom XML schema

I am a strong proponent of using the JSON format in most cases, as it provides the most flexibility. It is especially useful for sending both HTML and data at the same time.

While jQuery does offer many Ajax-related convenience methods, the core $.ajax method is at the heart of all of them, and understanding it is imperative. We'll review it first, and then touch briefly on the convenience methods.

I generally use the $.ajax method and do not use convenience methods. As you'll see, it offers features that the convenience methods do not, and its syntax is more easily understandable, in my opinion.

jQuery’s core $.ajax method is a powerful and straightforward way of creating Ajax requests. It takes a configuration object that contains all the instructions jQuery requires to complete the request. The $.ajax method is particularly valuable because it offers the ability to specify both success and failure callbacks. Also, its ability to take a configuration object that can be defined separately makes it easier to write reusable code. For complete documentation of the configuration options, visit http://api.jquery.com/jQuery.ajax/.


Note

A note about the dataType setting: if the server sends back data that is in a different format than you specify, your code may fail, and the reason will not always be clear, because the HTTP response code will not show an error. When working with Ajax requests, make sure your server is sending back the data type you're asking for, and verify that the Content-type header is accurate for the data type. For example, for JSON data, the Content-type header should beapplication/json.

There are many, many options for the $.ajax method, which is part of its power. For a complete list of options, visit http://api.jquery.com/jQuery.ajax/; here are several that you will use frequently:

async

Set to false if the request should be sent synchronously. Defaults to true. Note that if you set this option to false, your request will block execution of other code until the response is received.

cache

Whether to use a cached response if available. Defaults to true for all dataTypes except "script" and "jsonp". When set to false, the URL will simply have a cachebusting parameter appended to it.

complete

A callback function to run when the request is complete, regardless of success or failure. The function receives the raw request object and the text status of the request.

context

The scope in which the callback function(s) should run (i.e. what this will mean inside the callback function(s)). By default, this inside the callback function(s) refers to the object originally passed to $.ajax.

data

The data to be sent to the server. This can either be an object or a query string, such asfoo=bar&baz=bim.

dataType

The type of data you expect back from the server. By default, jQuery will look at the MIME type of the response if no dataType is specified.

error

A callback function to run if the request results in an error. The function receives the raw request object and the text status of the request.

jsonp

The callback name to send in a query string when making a JSONP request. Defaults to "callback".

success

A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the dataType was JSON), as well as the text status of the request and the raw request object.

timeout

The time in milliseconds to wait before considering the request a failure.

traditional

Set to true to use the param serialization style in use prior to jQuery 1.4. For details, seehttp://api.jquery.com/jQuery.param/.

type

The type of the request, "POST" or "GET". Defaults to "GET". Other request types, such as "PUT" and "DELETE" can be used, but they may not be supported by all browsers.

url

The URL for the request.

The url option is the only required property of the $.ajax configuration object; all other properties are optional.

If you don't need the extensive configurability of $.ajax, and you don't care about handling errors, the Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. These methods are just "wrappers" around the core $.ajax method, and simply pre-set some of the options on the $.ajax method.

The convenience methods provided by jQuery are:

$.get

Perform a GET request to the provided URL.

$.post

Perform a POST request to the provided URL.

$.getScript

Add a script to the page.

$.getJSON

Perform a GET request, and expect JSON to be returned.

In each case, the methods take the following arguments, in order:

url

The URL for the request. Required.

data

The data to be sent to the server. Optional. This can either be an object or a query string, such asfoo=bar&baz=bim.

Note

This option is not valid for $.getScript.

success callback

A callback function to run if the request succeeds. Optional. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.

data type

The type of data you expect back from the server. Optional.

Note

This option is only applicable for methods that don't already specify the data type in their name.


jQuery’s ajax capabilities can be especially useful when dealing with forms. The jQuery Form Pluginis a well-tested tool for adding Ajax capabilities to forms, and you should generally use it for handling forms with Ajax rather than trying to roll your own solution for anything remotely complex. That said, there are a two jQuery methods you should know that relate to form processing in jQuery:$.fn.serialize and $.fn.serializeArray.



The notation for creating a typical plugin is as follows:

(function($){
    $.fn.myNewPlugin = function() {
        return this.each(function(){
            // do something
        });
    };
}(jQuery));

Don't let that confuse you though. The point of a jQuery plugin is to extend jQuery's prototype object, and that's what's happening on this line:

$.fn.myNewPlugin = function() { //...

We wrap this assignment in an immediately-invoked function:

(function($){
    //...
}(jQuery));

This has the effect of creating a "private" scope that allows us to extend jQuery using the dollar symbol without having to risk the possibility that the dollar has been over-written by another library.

So our actual plugin, thus far, is this:

$.fn.myNewPlugin = function() {
    return this.each(function(){
        // do something
    });
};

The this keyword within the new plugin refers to the jQuery object on which the plugin is being called.

var somejQueryObject = $('#something');

$.fn.myNewPlugin = function() {
    alert(this === somejQueryObject);
};

somejQueryObject.myNewPlugin(); // alerts 'true'

Your typical jQuery object will contain references to any number of DOM elements, and that's why jQuery objects are often referred to as collections.

So, to do something with a collection we need to loop through it, which is most easily achieved using jQuery's each() method:

$.fn.myNewPlugin = function() {
    return this.each(function(){
    
    });
};

jQuery's each() method, like most other jQuery methods, returns a jQuery object, thus enabling what we've all come to know and love as 'chaining' ($(...).css().attr()...). We wouldn't want to break this convention so we return the this object. Within this loop you can do whatever you want with each element. Here's an example of a small plugin using some of the techniques we've discussed:

(function($){
    $.fn.showLinkLocation = function() {
        return this.filter('a').each(function(){
            $(this).append(
                ' (' + $(this).attr('href') + ')'
            );
        });
    };
}(jQuery));
    
// Usage example:
$('a').showLinkLocation();

This handy plugin goes through all anchors in the collection and appends the href attribute in brackets.

<!-- Before plugin is called: -->
<a href="page.html">Foo</a>
    
<!-- After plugin is called: -->
<a href="page.html">Foo (page.html)</a>

Our plugin can be optimised though:

(function($){
    $.fn.showLinkLocation = function() {
        return this.filter('a').append(function(){
              return ' (' + this.href + ')';
        });
    };
}(jQuery));

We're using the append method's capability to accept a callback, and the return value of that callback will determine what is appended to each element in the collection. Notice also that we're not using the attr method to retrieve the href attribute, because the native DOM API gives us easy access with the aptly named href property.

Here's another example of a plugin. This one doesn't require us to loop through every elememt with the each() method. Instead, we're simply going to delegate to other jQuery methods directly:

(function($){
    $.fn.fadeInAndAddClass = function(duration, className) {
        return this.fadeIn(duration, function(){
            $(this).addClass(className);
        });
    };
}(jQuery));
    
// Usage example:
$('a').fadeInAndAddClass(400, 'finishedFading');

Sometimes you want to make a piece of functionality available throughout your code; for example, perhaps you want a single method you can call on a jQuery selection that performs a series of operations on the selection. In this case, you may want to write a plugin.

Most plugins are simply methods created in the $.fn namespace. jQuery guarantees that a method called on a jQuery object will be able to access that jQuery object as this inside the method. In return, your plugin needs to guarantee that it returns the same object it received, unless explicitly documented otherwise.

Here is an example of a simple plugin:


For more on plugin development, read Mike Alsup's essential post, A Plugin Development Pattern. In it, he creates a plugin called $.fn.hilight, which provides support for the metadata plugin if it's present, and provides a centralized method for setting global and instance options for the plugin.


While most existing jQuery plugins are stateless — that is, we call them on an element and that is the extent of our interaction with the plugin — there’s a large set of functionality that doesn’t fit into the basic plugin pattern.

In order to fill this gap, jQuery UI has implemented a more advanced plugin system. The new system manages state, allows multiple functions to be exposed via a single plugin, and provides various extension points. This system is called the widget factory and is exposed asjQuery.widget as part of jQuery UI 1.8; however, it can be used independently of jQuery UI.

To demonstrate the capabilities of the widget factory, we'll build a simple progress bar plugin.

To start, we’ll create a progress bar that just lets us set the progress once. As we can see below, this is done by calling jQuery.widget with two parameters: the name of the plugin to create and an object literal containing functions to support our plugin. When our plugin gets called, it will create a new plugin instance and all functions will be executed within the context of that instance. This is different from a standard jQuery plugin in two important ways. First, the context is an object, not a DOM element. Second, the context is always a single object, never a collection.


The name of the plugin must contain a namespace; in this case we’ve used the nmk namespace. There is a limitation that namespaces be exactly one level deep — that is, we can't use a namespace like nmk.foo. We can also see that the widget factory has provided two properties for us.this.element is a jQuery object containing exactly one element. If our plugin is called on a jQuery object containing multiple elements, a separate plugin instance will be created for each element, and each instance will have its own this.element. The second property, this.options, is a hash containing key/value pairs for all of our plugin’s options. These options can be passed to our plugin as shown here.

Note

In our example we use the nmk namespace. The ui namespace is reserved for official jQuery UI plugins. When building your own plugins, you should create your own namespace. This makes it clear where the plugin came from and whether it is part of a larger collection.


When we call jQuery.widget it extends jQuery by adding a method to jQuery.fn (the same way we'd create a standard plugin). The name of the function it adds is based on the name you pass to jQuery.widget, without the namespace; in our case it will createjQuery.fn.progressbar. The options passed to our plugin get set in this.options inside of our plugin instance. As shown below, we can specify default values for any of our options. When designing your API, you should figure out the most common use case for your plugin so that you can set appropriate default values and make all options truly optional.


Now that we can initialize our progress bar, we’ll add the ability to perform actions by calling methods on our plugin instance. To define a plugin method, we just include the function in the object literal that we pass to jQuery.widget. We can also define “private” methods by prepending an underscore to the function name.


To call a method on a plugin instance, you pass the name of the method to the jQuery plugin. If you are calling a method that accepts parameters, you simply pass those parameters after the method name.


Note

Executing methods by passing the method name to the same jQuery function that was used to initialize the plugin may seem odd. This is done to prevent pollution of the jQuery namespace while maintaining the ability to chain method calls.

One of the easiest ways to make your plugin extensible is to add callbacks so users can react when the state of your plugin changes. We can see below how to add a callback to our progress bar to signify when the progress has reached 100%. The _trigger method takes three parameters: the name of the callback, a native event object that initiated the callback, and a hash of data relevant to the event. The callback name is the only required parameter, but the others can be very useful for users who want to implement custom functionality on top of your plugin. For example, if we were building a draggable plugin, we could pass the native mousemove event when triggering a drag callback; this would allow users to react to the drag based on the x/y coordinates provided by the event object.


Callback functions are essentially just additional options, so you can get and set them just like any other option. Whenever a callback is executed, a corresponding event is triggered as well. The event type is determined by concatenating the plugin name and the callback name. The callback and event both receive the same two parameters: an event object and a hash of data relevant to the event, as we’ll see below.

If your plugin has functionality that you want to allow the user to prevent, the best way to support this is by creating cancelable callbacks. Users can cancel a callback, or its associated event, the same way they cancel any native event: by calling event.preventDefault() or using return false. If the user cancels the callback, the _trigger method will return false so you can implement the appropriate functionality within your plugin.


Please visit http://github.com/rmurphey/jqfundamentals to contribute!

This chapter covers a number of jQuery and JavaScript best practices, in no particular order. Many of the best practices in this chapter are based on the jQuery Anti-Patterns for Performancepresentation by Paul Irish.

Selector optimization is less important than it used to be, as more browser implementdocument.querySelectorAll() and the burden of selection shifts from jQuery to the browser. However, there are still some tips to keep in midn.

When you move beyond adding simple enhancements to your website with jQuery and start developing full-blown client-side applications, you need to consider how to organize your code. In this chapter, we'll take a look at various code organization patterns you can use in your jQuery application and explore the RequireJS dependency management and build system.

The first step to code organization is separating pieces of your application into distinct pieces; sometimes, even just this effort is sufficient to lend

An object literal is perhaps the simplest way to encapsulate related code. It doesn't offer any privacy for properties or methods, but it's useful for eliminating anonymous functions from your code, centralizing configuration options, and easing the path to reuse and refactoring.


The object literal above is simply an object assigned to a variable. The object has one property and several methods. All of the properties and methods are public, so any part of your application can see the properties and call methods on the object. While there is an init method, there's nothing requiring that it be called before the object is functional.

How would we apply this pattern to jQuery code? Let's say that we had this code written in the traditional jQuery style:

// clicking on a list item loads some content
// using the list item's ID and hides content
// in sibling list items
$(document).ready(function() {
  $('#myFeature li')
    .append('<div/>')
    .click(function() {
      var $this = $(this);
      var $div = $this.find('div');
      $div.load('foo.php?item=' +
        $this.attr('id'), 
        function() {
          $div.show();
          $this.siblings()
            .find('div').hide();
        }
      );
    });
});

If this were the extent of our application, leaving it as-is would be fine. On the other hand, if this was a piece of a larger application, we'd do well to keep this functionality separate from unrelated functionality. We might also want to move the URL out of the code and into a configuration area. Finally, we might want to break up the chain to make it easier to modify pieces of the functionality later.


The first thing you'll notice is that this approach is obviously far longer than the original — again, if this were the extent of our application, using an object literal would likely be overkill. Assuming it's not the extent of our application, though, we've gained several things:

  • We've broken our feature up into tiny methods. In the future, if we want to change how content is shown, it's clear where to change it. In the original code, this step is much harder to locate.

  • We've eliminated the use of anonymous functions.

  • We've moved configuration options out of the body of the code and put them in a central location.

  • We've eliminated the constraints of the chain, making the code easier to refactor, remix, and rearrange.

For non-trivial features, object literals are a clear improvement over a long stretch of code stuffed in a $(document).ready() block, as they get us thinking about the pieces of our functionality. However, they aren't a whole lot more advanced than simply having a bunch of function declarations inside of that $(document).ready() block.

The module pattern overcomes some of the limitations of the object literal, offering privacy for variables and functions while exposing a public API if desired.


In the example above, we self-execute an anonymous function that returns an object. Inside of the function, we define some variables. Because the variables are defined inside of the function, we don't have access to them outside of the function unless we put them in the return object. This means that no code outside of the function has access to the privateThing variable or to thechangePrivateThing function. However, sayPrivateThing does have access toprivateThing and changePrivateThing, because both were defined in the same scope assayPrivateThing.

This pattern is powerful because, as you can gather from the variable names, it can give you private variables and functions while exposing a limited API consisting of the returned object's properties and methods.

Below is a revised version of the previous example, showing how we could create the same feature using the module pattern while only exposing one public method of the module,showItemByIndex().


When a project reaches a certain size, managing the script modules for a project starts to get tricky. You need to be sure to sequence the scripts in the right order, and you need to start seriously thinking about combining scripts together into a bundle for deployment, so that only one or a very small number of requests are made to load the scripts. You may also want to load code on the fly, after page load.

RequireJS, a dependency management tool by James Burke, can help you manage the script modules, load them in the right order, and make it easy to combine the scripts later via the RequireJS optimization tool without needing to change your markup. It also gives you an easy way to load scripts after the page has loaded, allowing you to spread out the download size over time.

RequireJS has a module system that lets you define well-scoped modules, but you do not have to follow that system to get the benefits of dependency management and build-time optimizations. Over time, if you start to create more modular code that needs to be reused in a few places, the module format for RequireJS makes it easy to write encapsulated code that can be loaded on the fly. It can grow with you, particularly if you want to incorporate internationalization (i18n) string bundles, to localize your project for different languages, or load some HTML strings and make sure those strings are available before executing code, or even use JSONP services as dependencies.

The easiest way to use RequireJS with jQuery is to download a build of jQuery that has RequireJS built in. This build excludes portions of RequireJS that duplicate jQuery functionality. You may also find it useful to download a sample jQuery project that uses RequireJS.

Using RequireJS in your page is simple: just include the jQuery that has RequireJS built in, then require your application files. The following example assumes that the jQuery build, and your other scripts, are all in a scripts/ directory.


The call to require(["app"]) tells RequireJS to load the scripts/app.js file. RequireJS will load any dependency that is passed to require() without a .js extension from the same directory as require-jquery.js, though this can be configured to behave differently. If you feel more comfortable specifying the whole path, you can also do the following:

<script>require(["scripts/app.js"]);</script>

What is in app.js? Another call to require.js to load all the scripts you need and any init work you want to do for the page. This example app.js script loads two plugins, jquery.alpha.jsand jquery.beta.js (not the names of real plugins, just an example). The plugins should be in the same directory as require-jquery.js:


RequireJS makes it easy to define reusable modules via require.def(). A RequireJS module can have dependencies that can be used to define a module, and a RequireJS module can return a value — an object, a function, whatever — that can then be consumed by yet other modules.

If your module does not have any dependencies, then just specify the name of the module as the first argument to require.def(). The second argument is just an object literal that defines the module's properties. For example:

Example 10.7. Defining a RequireJS module that has no dependencies

require.def("my/simpleshirt",
    {
        color: "black",
        size: "unisize"
    }
);

This example would be stored in a my/simpleshirt.js file.

If your module has dependencies, you can specify the dependencies as the second argument torequire.def() (as an array) and then pass a function as the third argument. The function will be called to define the module once all dependencies have loaded. The function receives the values returned by the dependencies as its arguments (in the same order they were required in the array), and the function should return an object that defines the module.


In this example, a my/shirt module is created. It depends on my/cart and my/inventory. On disk, the files are structured like this:

my/cart.js
my/inventory.js
my/shirt.js

The function that defines my/shirt is not called until the my/cart and my/inventorymodules have been loaded, and the function receives the modules as the cart and inventoryarguments. The order of the function arguments must match the order in which the dependencies were required in the dependencies array. The object returned by the function call defines the my/shirt module. Be defining modules in this way, my/shirt does not exist as a global object. Modules that define globals are explicitly discouraged, so multiple versions of a module can exist in a page at a time.

Modules do not have to return objects; any valid return value from a function is allowed.


Only one module should be required per JavaScript file.


Once you incorporate RequireJS for dependency management, your page is set up to be optimized very easily. Download the RequireJS source and place it anywhere you like, preferrably somewhere outside your web development area. For the purposes of this example, the RequireJS source is placed as a sibling to the webapp directory, which contains the HTML page and the scripts directory with all the scripts. Complete directory structure:

requirejs/ (used for the build tools)
webapp/app.html
webapp/scripts/app.js
webapp/scripts/require-jquery.js
webapp/scripts/jquery.alpha.js
webapp/scripts/jquery.beta.js

Then, in the scripts directory that has require-jquery.js and app.js, create a file called app.build.js with the following contents:


To use the build tool, you need Java 6 installed. Closure Compiler is used for the JavaScript minification step (if optimize: "none" is commented out), and it requires Java 6.

To start the build, go to the webapp/scripts directory, execute the following command:

# non-windows systems
../../requirejs/build/build.sh app.build.js

# windows systems
..\..\requirejs\build\build.bat app.build.js

Now, in the webapp-build directory, app.js will have the app.js contents, jquery.alpha.jsand jquery.beta.js inlined. If you then load the app.html file in the webapp-builddirectory, you should not see any network requests for jquery.alpha.js andjquery.beta.js.

We’re all familiar with the basic events — click, mouseover, focus, blur, submit, etc. — that we can latch on to as a user interacts with the browser. Custom events open up a whole new world of event-driven programming. In this chapter, we’ll use jQuery’s custom events system to make a simple Twitter search application.

It can be difficult at first to understand why you'd want to use custom events, when the built-in events seem to suit your needs just fine. It turns out that custom events offer a whole new way of thinking about event-driven JavaScript. Instead of focusing on the element that triggers an action, custom events put the spotlight on the element being acted upon. This brings a bevy of benefits, including:

  • Behaviors of the target element can easily be triggered by different elements using the same code.

  • Behaviors can be triggered across multiple, similar, target elements at once.

  • Behaviors are more clearly associated with the target element in code, making code easier to read and maintain.

Why should you care? An example is probably the best way to explain. Suppose you have a lightbulb in a room in a house. The lightbulb is currently turned on, and it’s controlled by two three-way switches and a clapper:

<div class="room" id="kitchen">
    <div class="lightbulb on"></div>
    <div class="switch"></div>
    <div class="switch"></div>
    <div class="clapper"></div>
</div>

Triggering the clapper or either of the switches will change the state of the lightbulb. The switches and the clapper don’t care what state the lightbulb is in; they just want to change the state.

Without custom events, you might write some code like this:

$('.switch, .clapper').click(function() {
    var $light = $(this).parent().find('.lightbulb');
    if ($light.hasClass('on')) {
        $light.removeClass('on').addClass('off');
    } else {
        $light.removeClass('off').addClass('on');
    }
});

With custom events, your code might look more like this:

$('.lightbulb').bind('changeState', function(e) {
    var $light = $(this);
    if ($light.hasClass('on')) {
        $light.removeClass('on').addClass('off');
    } else {
        $light.removeClass('off').addClass('on');
    }
});

$('.switch, .clapper').click(function() { 
    $(this).parent().find('.lightbulb').trigger('changeState');
});

This last bit of code is not that exciting, but something important has happened: we’ve moved the behavior of the lightbulb to the lightbulb, and away from the switches and the clapper.

Let’s make our example a little more interesting. We’ll add another room to our house, along with a master switch, as shown here:

<div class="room" id="kitchen">
    <div class="lightbulb on"></div>
    <div class="switch"></div>
    <div class="switch"></div>
    <div class="clapper"></div>
</div>
<div class="room" id="bedroom">
    <div class="lightbulb on"></div>
    <div class="switch"></div>
    <div class="switch"></div>
    <div class="clapper"></div>
</div>
<div id="master_switch"></div>

If there are any lights on in the house, we want the master switch to turn all the lights off; otherwise, we want it to turn all lights on. To accomplish this, we’ll add two more custom events to the lightbulbs: turnOn and turnOff. We’ll make use of them in the changeState custom event, and use some logic to decide which one the master switch should trigger:

$('.lightbulb')
    .bind('changeState', function(e) {
        var $light = $(this);
        if ($light.hasClass('on')) {
            $light.trigger('turnOff');
        } else {
            $light.trigger('turnOn');
        }
    })
    .bind('turnOn', function(e) {
        $(this).removeClass('off').addClass('on');
    })
    .bind('turnOff', function(e) {
        $(this).removeClass('off').addClass('on');
    });
 
$('.switch, .clapper').click(function() { 
    $(this).parent().find('.lightbulb').trigger('changeState');
});
 
$('#master_switch').click(function() {
    if ($('.lightbulb.on').length) {
        $('.lightbulb').trigger('turnOff');
    } else {
        $('.lightbulb').trigger('turnOn');
    }
});

Note how the behavior of the master switch is attached to the master switch; the behavior of a lightbulb belongs to the lightbulbs.

Note

If you’re accustomed to object-oriented programming, you may find it useful to think of custom events as methods of objects. Loosely speaking, the object to which the method belongs is created via the jQuery selector. Binding the changeState custom event to all $(‘.light’) elements is akin to having a class called Light with a method of changeState, and then instantiating newLight objects for each element with a classname of light.

To demonstrate the power of custom events, we’re going to create a simple tool for searching Twitter. The tool will offer several ways for a user to add search terms to the display: by entering a search term in a text box, by entering multiple search terms in the URL, and by querying Twitter for trending terms.

The results for each term will be shown in a results container; these containers will be able to be expanded, collapsed, refreshed, and removed, either individually or all at once.

When we’re done, it will look like this:


We’ll start with some basic HTML:

<h1>Twitter Search</h1>
<input type="button" id="get_trends" 
    value="Load Trending Terms" />
 
<form>
    <input type="text" class="input_text" 
        id="search_term" />
    <input type="submit" class="input_submit" 
        value="Add Search Term" />
</form>
 
<div id="twitter">
    <div class="template results">
        <h2>Search Results for 
        <span class="search_term"></span></h2>
    </div>
</div>

This gives us a container (#twitter) for our widget, a template for our results containers (hidden via CSS), and a simple form where users can input a search term. (For the sake of simplicity, we’re going to assume that our application is JavaScript-only and that our users will always have CSS.)

There are two types of objects we’ll want to act on: the results containers, and the Twitter container.

The results containers are the heart of the application. We’ll create a plugin that will prepare each results container once it’s added to the Twitter container. Among other things, it will bind the custom events for each container and add the action buttons at the top right of each container. Each results container will have the following custom events:

refresh

Mark the container as being in the “refreshing” state, and fire the request to fetch the data for the search term.

populate

Receive the returned JSON data and use it to populate the container.

remove

Remove the container from the page after the user verifies the request to do so. Verification can be bypassed by passing true as the second argument to the event handler. The remove event also removes the term associated with the results container from the global object containing the search terms.

collapse

Add a class of collapsed to the container, which will hide the results via CSS. It will also turn the container’s “Collapse” button into an “Expand” button.

expand

Remove the collapsed class from the container. It will also turn the container’s “Expand” button into a “Collapse” button.

The plugin is also responsible for adding the action buttons to the container. It binds a click event to each action’s list item, and uses the list item’s class to determine which custom event will be triggered on the corresponding results container.

$.fn.twitterResult = function(settings) {
    return $(this).each(function() {
        var $results = $(this),
            $actions = $.fn.twitterResult.actions = 
                $.fn.twitterResult.actions || 
                $.fn.twitterResult.createActions(),
            $a = $actions.clone().prependTo($results),
            term = settings.term;

        $results.find('span.search_term').text(term);

        $.each(
            ['refresh', 'populate', 'remove', 'collapse', 'expand'], 
            function(i, ev) { 
                $results.bind(
                    ev, 
                    { term : term },
                    $.fn.twitterResult.events[ev]
                ); 
            }
        );

        // use the class of each action to figure out 
        // which event it will trigger on the results panel
        $a.find('li').click(function() {
            // pass the li that was clicked to the function
            // so it can be manipulated if needed
            $results.trigger($(this).attr('class'), [ $(this) ]);
        });
    });
};

$.fn.twitterResult.createActions = function() {
    return $('<ul class="actions" />').append(
        '<li class="refresh">Refresh</li>' +
        '<li class="remove">Remove</li>' +
        '<li class="collapse">Collapse</li>'
    );
};

$.fn.twitterResult.events = {
    refresh : function(e) {
           // indicate that the results are refreshing
        var $this = $(this).addClass('refreshing');

        $this.find('p.tweet').remove();
        $results.append('<p class="loading">Loading ...</p>');

        // get the twitter data using jsonp
        $.getJSON(
            'http://search.twitter.com/search.json?q=' +                     
                escape(e.data.term) + '&rpp=5&callback=?', 
            function(json) { 
                $this.trigger('populate', [ json ]); 
            }
        );
    },

    populate : function(e, json) {
        var results = json.results;
        var $this = $(this);

        $this.find('p.loading').remove();

        $.each(results, function(i,result) {
            var tweet = '<p class="tweet">' + 
                '<a href="http://twitter.com/' + 
                result.from_user + 
                '">' +
                result.from_user + 
                '</a>: ' +
                result.text + 
                ' <span class="date">' + 
                result.created_at + 
                '</span>' +
            '</p>';
            $this.append(tweet);
        });

        // indicate that the results 
        // are done refreshing
        $this.removeClass('refreshing');
    },

    remove : function(e, force) {
        if (
            !force &&     
            !confirm('Remove panel for term ' + e.data.term + '?')
        ) {
            return;
        }
        $(this).remove();

        // indicate that we no longer 
        // have a panel for the term
        search_terms[e.data.term] = 0;
    },

    collapse : function(e) {
        $(this).find('li.collapse').removeClass('collapse')
            .addClass('expand').text('Expand');

        $(this).addClass('collapsed');
    },

    expand : function(e) {
        $(this).find('li.expand').removeClass('expand')
            .addClass('collapse').text('Collapse');

        $(this).removeClass('collapsed');
    }
};

The Twitter container itself will have just two custom events:

getResults

Receives a search term and checks to determine whether there’s already a results container for the term; if not, adds a results container using the results template, set up the results container using the $.fn.twitterResult plugin discussed above, and then triggers the refresh event on the results container in order to actually load the results. Finally, it will store the search term so the application knows not to re-fetch the term.

getTrends

Queries Twitter for the top 10 trending terms, then iterates over them and triggers thegetResults event for each of them, thereby adding a results container for each term.

Here's how the Twitter container bindings look:

$('#twitter')
    .bind('getResults', function(e, term) {
        // make sure we don't have a box for this term already
        if (!search_terms[term]) { 
            var $this = $(this);
            var $template = $this.find('div.template');

            // make a copy of the template div
            // and insert it as the first results box
            $results = $template.clone().
                removeClass('template').
                insertBefore($this.find('div:first')).
                twitterResult({
                    'term' : term
                });

            // load the content using the "refresh" 
            // custom event that we bound to the results container
            $results.trigger('refresh');
            search_terms[term] = 1;
        }
    })
    .bind('getTrends', function(e) {
        var $this = $(this);
        $.getJSON('http://search.twitter.com/trends.json?callback=?', function(json) {
                var trends = json.trends; 
                $.each(trends, function(i, trend) {
                    $this.trigger('getResults', [ trend.name ]);
                });
            });
    });

So far, we’ve written a lot of code that does approximately nothing, but that’s OK. By specifying all the behaviors that we want our core objects to have, we’ve created a solid framework for rapidly building out the interface.

Let’s start by hooking up our text input and the “Load Trending Terms” button. For the text input, we’ll capture the term that was entered in the input and pass it as we trigger the Twitter container’sgetResults event. Clicking the “Load Trending Terms” will trigger the Twitter container’sgetTrends event:

$('form').submit(function(e) {
    e.preventDefault();
    var term = $('#search_term').val();
    $('#twitter').trigger('getResults', [ term ]);
});

$('#get_trends').click(function() {
    $('#twitter').trigger('getTrends'); 
});

By adding a few buttons with the appropriate IDs, we can make it possible to remove, collapse, expand, and refresh all results containers at once, as shown below. For the remove button, note how we’re passing a value of true to the event handler as its second argument, telling the event handler that we don’t want to verify the removal of individual containers.

$.each(['refresh', 'expand', 'collapse'], function(i, ev) {
    $('#' + ev).click(function(e) { $('#twitter div.results').trigger(ev); });
});

$('#remove').click(function(e) {
    if (confirm('Remove all results?')) {
        $('#twitter div.results').trigger('remove', [ true ]);
    }
});


[jQuery] 브라우져 알아내기

프로그래밍/Web 2009. 12. 17. 15:43 Posted by galad
var m_browser;
var m_version;

function detectBrowser() {
    if($.browser.msie) {
        m_browser = "msie";
    }
    else if($.browser.safari) {
        m_browser = "safari";
    }
    else if($.browser.opera) {
        m_browser = "opera";
    }
    else if($.browser.mozilla) {
        m_browser = "mozilla";
    }

    m_version = $.browser.version;

    //alert(m_browser + " " + m_version);
}

$.browser.mozilla
$.browser.version

http://visualjquery.com/ 여기서 Utilites > User Agent 참고
$(window).scrollTop()

간단하군....

[jQuery] jQuery를 이용한 ajax

프로그래밍/Web 2009. 12. 16. 11:20 Posted by galad
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

- json 형식으로 결과를 받겠다 해놓고, 결과가 json형식에 안맞아도 error.
- timeout 시간이 넘어가도 error. 처음엔 개발장비서 할 떄 계속 에러나서 원인을 못찾았었음. 주의할 것.

$.ajax외에도 $.post 같은 좀 더 간단한 jQuery 메소드가 있음.
http://www.ibm.com/developerworks/kr/library/wa-jquery3/
출처: http://whdrnr01.textcube.com/7?t=c&i=0

jQuery를 이용해서, div의 설정 변경을 통한 레이어 팝업.
ajax랑 함께 쓰면, ajax를 이용해서 데이터를 얻어온 후, div의 안에 원하는 형태로 데이터를 넣고 나서 보여주는 형식이 될 듯.

소스출처: http://yensdesign.com/tutorials/popupjquery/

/**
 * jQuery를 이용한 초기 설정
 */
$(document).ready(function() {
    // 마우스 오버 시 배경색 반전
    $(".catLabel1").hover(
        function() { // hover 시
            $(this).css({"background-color":"yellow", "font-weight":"bolder" });
        },
        function() { // out 시
            $(this).css({"background-color":"white", "font-weight":"normal" });
        }
    );

    $(".catLabel2").hover(
            function() { // hover 시
                $(this).css({"background-color":"yellow", "font-weight":"bolder" });
            },
            function() { // out 시
                $(this).css({"background-color":"white", "font-weight":"normal" });
            }
        );
   
    // 표준분류 선택 시 전시 카테고리 목록을 표시한다.
    $(".catLabel1").click(showAlert);
    $(".catLabel2").click(ajaxGetDpCatList);
   
    //CLOSING POPUP
    //Click the x event!
    /*$("#popupContactClose").click(function(){
        disablePopup();
    });*/
    //Click out event!
    $("#backgroundPopup").click(function(){
        disablePopup();
    });
    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });
});

/**
 * 표준 분류의 대분류 선택 시 경고 메시지
 */
function showAlert() {
    alert("표준 카테고리의 중분류를 선택해 주세요.");
}

/**
 * ajax로 전시 카테고리 목록 얻어오기
 */
function ajaxGetDpCatList() {
    //alert("ajax로 전체 전시 카테고리 정보 얻기");
    //alert($(this).attr("title"));
   
    var selectedCatId = $(this).attr("title");
    $("#selectedCatId").val(selectedCatId);
    //alert($("#selectedCatId").val());
   
    $.ajax({
        url: '${pageContext.request.contextPath}/categoryMapping/getDpCatList.omp',
        type: 'POST',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            alert('전시 카테고리 정보를 얻는 중에 오류가 발생했습니다.');
        },
        success: function(data){
            //alert(data);
            //alert(data.dpCatList[0].key + " " + data.dpCatList[0].value);
            showDpCatList(data);
        }
    });
}

/**
 * 전시 카테고리 목록 표시
 */
function showDpCatList(data) {
    //alert($("#selectedCatId").val());
    //alert(data.dpCatList.length);

    var dpCatListPopup = document.getElementById("dpCatListPopup");

    // dpCatListPopup 의 내용을 비움. 안하면 계속 늘어남
    deleteNodes(dpCatListPopup, "span");
    deleteNodes(dpCatListPopup, "br");

    // 전시 카테고리 표시용 목록 만들기
    var list = data.dpCatList;
    for(var i = 0; i < list.length; i++) {
        var key = list[i].key;
        var label = list[i].value;

        var el = document.createElement("span");
        el.setAttribute("title", key);
        el.setAttribute("class", "dpCatLabel");
        //el.setAttribute("onclick", "alert('TEST');"); // DOESN'T WORK. onclick is not attribute.
        el.onclick=function(){alert("TEST");};
        var txt = document.createTextNode(label);
        el.appendChild(txt);

        dpCatListPopup.appendChild(el);
        dpCatListPopup.appendChild(document.createElement("br"));
    }

    setPopupPosition();
    loadPopup();
}

function deleteNodes(parentNode, tag) {
    var nodes = parentNode.getElementsByTagName(tag);
    var length = nodes.length;
   
    // 이건 nodes가 실시간으로 줄어들면서 length 자체가 줄어든다.
    // 따라서 아래의 for문에서 기존 nodes의 갯수만큼 루핑하면서 0번만 계속 지움.
    // i번을 삭제하면 stack overflow 남
    /*for(var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        parentNode.removeChild(node);
    }*/
   
    for(var i = 0; i < length; i++) {
        var node = nodes[0];
        parentNode.removeChild(node);
    }
}

//0 means disabled; 1 means enabled;
var popupStatus = 0;

/**
 * set popup position
 */
function setPopupPosition(){
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.scrollHeight; //clientHeight;
    var popupHeight = $("#dpCatListPopup").height();
    var popupWidth = $("#dpCatListPopup").width();
   
    //centering
    $("#dpCatListPopup").css({
        "position": "absolute",
        "top": 0, //windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2
    });

    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
   
}

function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("slow");
        $("#dpCatListPopup").fadeIn("slow");
        popupStatus = 1;
    }
}

function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#dpCatListPopup").fadeOut("slow");
       
        popupStatus = 0;
    }
}

setPopupPosition() 으로 위치 설정.
loadPopup() 으로 보이기
disablePopup() 으로 숨기기

backgroundPopup 랑 dpCatListPopup 는 div의 id.

'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery를 이용한 ajax  (0) 2009.12.16
[javascript] HTML DOM 지우기  (0) 2009.12.16
[json] json 사용법  (0) 2009.12.15
[html] html 특수기호  (3) 2009.09.08
[servlet] servlet  (0) 2009.09.04

[jQuery] jQuery 예제 01

프로그래밍/Web 2009. 7. 17. 16:49 Posted by galad
출처: http://www.jiny.kr/jiny/417
위의 출처의 예제를 직접 해보면서 작성한 소스를 붙여넣고, 몇몇 사항들은 삭제/추가하였음...
문제있으면 알려주시길...

http://hanjiq.egloos.com/2108204
http://orangenius.tistory.com/5
http://jqueryui.com/home


size( ) 
Returns: Number
size( ), 실행후 숫자를 반환

The number of elements in the jQuery object.
매치되어진 원소들의 갯수를 반환한다.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>01</title>

<style>
body { cursor:pointer; }
div { width:50px; height:30px; margin:5px; float:left; background:blue; }
span { color:red; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $(document.body).click(function() {
        $(document.body).append($("<div>"));
        var n = $("div").size();
        //var n = $("div").length; // size()와 같다
        $("span").text("There are " + n + " divs. Click to add more.");
    }).click(); // 한 번 강제로 클릭 - 아래의 body에는 div가 3개인데 실행되면서 4개로 화면에 표시된다.
});
</script>

</head>
<body>

<span></span>
<div></div>
<div></div>
<div></div>

</body>
</html>
/JQueryTest01/WebContent/Example01/01.html

get( ) 
Returns: Array<Element>
get( ), 실행후 원소 배열 반환

Access all matched DOM elements.
매치되는 모든 문서 원소들을 배열로 반환한다
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>02</title>

<style>
span { color:red; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    disp($("div").get().reverse()); // get으로 array를 얻어서, reverse로 순서뒤집기
});

function disp(divs) {
    var a = [];
    for(var i = 0; i < divs.length; i++) {
        a.push(divs[i].innerHTML);
    }

    $("span").text(a.join(" "));
}
</script>

</head>
<body>

Reversed - <span></span>
<div>One</div>
<div>Two</div>
<div>2.5</div>
<div>Three</div>

</body>
</html>
/JQueryTest01/WebContent/Example01/02.html

get( index ) 
Returns: Element
get( 인덱스 ), 실행후 매치 되는 원소를 반환

Access a single matched DOM element at a specified index in the matched set.
매치되는 원소들 중 주어진 인덱스에 해당하는 하나의 원소만 반환한다.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>02</title>

<style>
span { color:red; }
div { background:yellow; }
</style>
 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("*", document.body).click(function (e) {
        e.stopPropagation(); // 이벤트 정지
        var domEl = $(this).get(0); // 클릭한 객체를 받음
        $("span:first").text("Clicked on - " + domEl.tagName); // 태그명 표시
    });
});
</script>

</head>
<body>

<span> </span>
<p>In this paragraph is an <span>important</span> section</p>
<div><input type="text" /></div>

</body>
</html>

event.stopPropagation

https://developer.mozilla.org/en/DOM:event.stopPropagation
jQuery함수가 아니라 DOM 객체 함수임.

Prevents further propagation of the current event.
현재 이벤트가 더 진행하는 것을 방지
<html>
<head>
<title>Event Propagation</title>

<style type="text/css">
 #t-daddy { border: 1px solid red }
 #c1 { background-color: pink; }
</style>

<script type="text/javascript">

function stopEvent(ev) {
  c2 = document.getElementById("c2");
  c2.innerHTML = "hello";

  // this ought to keep t-daddy from getting the click.
  ev.stopPropagation();
  alert("event propagation halted.");
}

function load() {
  elem = document.getElementById("tbl1");
  elem.addEventListener("click", stopEvent, false);
}
</script>
</head>

<body onload="load();">

<table id="t-daddy" onclick="alert('hi');">
 <tr id="tbl1">
  <td id="c1">one</td>
 </tr>
 <tr>
  <td id="c2">two</td>
 </tr>
</table>

</body>
</html>
/JQueryTest01/WebContent/Example01/03.html

출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using the tablesorter plugin
http://tablesorter.com/docs/
$("#myTable").tablesorter();
---------------------------------------------
<table id="myTable">
<thead>
<tr>
    <th>Last Name</th>
    <th>First Name</th>
    <th>Email</th>
    <th>Due</th>
    <th>Web Site</th>
</tr>
</thead>
<tbody>
<tr>
    <td>Smith</td>
    <td>John</td>
    <td>jsmith@gmail.com</td>
    <td>$50.00</td>
    <td>http://www.jsmith.com</td>
</tr>
<tr>
    <td>Bach</td>
    <td>Frank</td>
    <td>fbach@yahoo.com</td>
    <td>$50.00</td>
    <td>http://www.frank.com</td>
</tr>
<tr>
    <td>Doe</td>
    <td>Jason</td>
    <td>jdoe@hotmail.com</td>
    <td>$100.00</td>
    <td>http://www.jdoe.com</td>
</tr>
<tr>
    <td>Conway</td>
    <td>Tim</td>
    <td>tconway@earthlink.net</td>
    <td>$50.00</td>
    <td>http://www.timconway.com</td>
</tr>
</tbody>
</table>
<thread> 태그 안에 있는 것을 클릭하면 테이블을 정렬한다. 신기하네...
숫자, 문자 등을 알아서 판별한다고 하는군. 상세한 것은 위의 링크를 참조.

$("#myTable").tablesorter( {sortList: [[0,0], [1,0]]} );
This tells tablesorter to sort on the first and second column in ascending order.
정렬 초기값 설정.

Sort multiple columns simultaneously by holding down the shift key and clicking a second, third or even fourth column header!
하나 선택해서 그걸 기준으로 정렬하고 쉬프트 클릭하고 다른 것 선택하면 계단식으로 정렬됨(기존 정렬을 기준으로 다시 정렬).

속도만 받쳐주면 테이블 정렬은 이걸로 해도 될듯?!
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Effects
$(document).ready(function(){
   $("a").toggle(function(){
     $(".stuff").hide('slow');
   },function(){
     $(".stuff").show('fast');
   });
 });
소스 버전이 옛날 것인가... 제대로 동작하질 않는군..

http://docs.jquery.com/Effects/toggle
위의 링크된 문서를 참고할 것

$(document).ready(function() {
    $("#btn1").click(function() {
        $("p").toggle();
        $("#hbtn").toggle();
    });
});

-----------------------------------------

<button id="btn1">Toggle</button>
<p class="tg">Hello</p>
<p class="tg" style="display: none;">Toggle!</p>
<p>AAA</p>
<p style="display: none;">BBB</p>
<button id="hbtn" style="display: none;">hidden button</button>
해보면 toggle()한 display:none이 아닌 것은 안보이게 되고, display:none이었던 것은 보이게된다.

var flip = 0;
$("button").click(function () {
    $("p").toggle( flip++ % 2 == 0 );
});
toggle(XXX)안에 식을 넣는 것도 가능. true면 보이고, false면 숨긴다.

$("button").click(function () {
    $("p").toggle("slow");
});
toggle("slow"). 천천히 사라지고 천천히 나타남.
slow, fast, normal 이 있고, 직접 밀리세컨드로 속도를 지정할 수 있다.

$("button").click(function () {
    $("p").toggle("slow", doCallback);
});

function doCallback() {
    // do something
    this; // DOM element
}
이런 식으로 토글 이펙트가 끝났을 때 실행될 callback 함수도 지정 가능.
여러 개가 토글 되는 경우 각각 실행됨.
사라지는 토글이라고 해서 사라지는 DOM의 callback만 실행되는 것이 아니라, 나타나는 DOM의 callback도 실행된다.
즉 어찌됐든 토글되는 모든 DOM의 callback이 실행됨.

기타 Effects는 아래 링크를 참조.
http://docs.jquery.com/Effects

Animate
// Using multiple unit types within one animation.
$("#go").click(function(){
    $("#block").animate({
        width: "70%",
        opacity: 0.4,
        marginLeft: "0.6in",
        fontSize: "3em",
        borderWidth: "10px"
    }, 1500 );
});
---------------------------------------------------
<button id="go">» Run</button>
<div id="block">Hello!</div>
#block이 초기 모양에서 animate({XXX}, YYY)에 설정된 모양(XXX)으로 변형된다. 이 때, YYY는 변형 시간(클 수록 천천히).

$("#go1").click(function(){
    $("#block1").animate( { width:"90%" }, { queue:false, duration:3000 } )
         .animate( { fontSize:"24px" }, 1500 )
         .animate( { borderRightWidth:"15px" }, 1500
    );
});

$("#go2").click(function(){
    $("#block2").animate( { width:"90%"}, 1000 )
         .animate( { fontSize:"24px" } , 1000 )
         .animate( { borderLeftWidth:"15px" }, 1000
    );
});

$("#go3").click(function(){
    $("#go1").add("#go2").click();
});

$("#go4").click(function(){
    $("div").css({width:"", fontSize:"", borderWidth:""});
});
---------------------------------------------------
<button id="go1">» Animate Block1</button>
<button id="go2">» Animate Block2</button>
<button id="go3">» Animate Both</button>
<button id="go4">» Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
$("#ID").animate({AAA},AAA).animate({BBB},BBB).animate({CCC},CCC); AAA, BBB, CCC의 순서대로 애니메이트됨.
queue:false 옵션이 있으면 순서 상관없이 동시에 애니메이트됨.

$("#go1").add("#go2").click(); go1과 go2를 동시에 클릭 이벤트 발생시킴.


animate()
Arguments:
paramsOptions
A set of style attributes that you wish to animate, and to what end.
duration (Optional)String, Number
A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
easing (Optional)String
The name of the easing effect that you want to use (plugin required). There are two built-in values, "linear" and "swing".
callback (Optional)Function
A function to be executed whenever the animation completes, executes once for each element animated against.

$("p").animate({
      "height": "toggle", "opacity": "toggle"
}, { duration: "slow" });
Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.
라는데, height랑 opacity를 토글하는게 무슨 효과인지 모르겠다.

나머진 위의 링크 참조...


'프로그래밍 > Web' 카테고리의 다른 글

[jQuery] jQuery 예제 01  (0) 2009.07.17
[jQuery] Getting Started with jQuery 04  (0) 2009.07.11
[jQuery] Getting Started with jQuery 02  (0) 2009.07.10
[jQuery] Getting Started with jQuery 01  (0) 2009.07.10
[jQuery] How jQuery Works  (0) 2009.07.06
출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Using Ajax
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>jQuery Starterkit</title>

<link rel="stylesheet" type="text/css" media="screen" href="css/screen.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
    // generate markup
    var ratingMarkup = ["Please rate: "];
    for(var i=1; i <= 5; i++) {
        ratingMarkup[ratingMarkup.length] = "<a href='#'>" + i + "</a> ";
    }
    var container = $("#rating");
    // add markup to container
    container.html(ratingMarkup.join(''));
   
    // add click handlers
    container.find("a").click(function(e) {
        e.preventDefault();
        // send requests
        $.post("starterkit/rate.php", {rating: $(this).html()}, function(xml) {
            // format result
            var result = [
                "Thanks for rating, current average: ",
                $("average", xml).text(),
                ", number of votes: ",
                $("count", xml).text()
            ];
            // output result
            $("#rating").html(result.join(''));
        } );
    });
});
</script>

</head>
<body>
<h1>jQuery Getting Started Example - rate me</h1>
<p>This example demonstrate basic use of AJAX. Click one of the links below to rate. The
number of rating and the average rating will be returned from the serverside script and displayed.</p>

<div id="rating">Container</div>

</body>
</html>
$("average", xml).text() -> 결과로 받은 xml에서 <average>XXX</average>를 찾아서 text 값을 가져온다.
딱히 구조(부모-자식)는 상관없는 듯.

기타 참고 사항.
ajax 사용 시 주의점

A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function.
Example:
function addClickHandlers() {
   $("a.remote", this).click(function() {
     $("#target").load(this.href, addClickHandlers);
   });
 }
 $(document).ready(addClickHandlers);

Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading.

Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually.

Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function:
// get some data
 var foobar = ...;
 
 // specify handler, it needs data as a paramter
 function handler(data) {
   //...
 }
 
 // add click handler and pass foobar!
 $('a').click(function(){
   handler(foobar);
 });
 
 // if you need the context of the original handler, use apply:
 $('a').click(function(){
   handler.apply(this, [foobar]);
 });


출처: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

간단한 부분은 제외.

Using selectors and events

$(document).ready(function() {
   $("#orderedlist").addClass("red");
 });
id가 orderedlist 인 것을 찾아서 red 클래스를 추가

$(document).ready(function() {
   $("#orderedlist > li").addClass("blue");
 });
orderedlist 가 갖는 모든 li 태그에 blue 클래스 추가

$(document).ready(function() {
   $("#orderedlist li:last").hover(function() {
     $(this).addClass("green");
   },function(){
     $(this).removeClass("green");
   });
 });
orderedlist 가 갖는 마지막 li 태그 위에 커서가 오면 green 클래스를 추가하고, 커서가 나가면 green 클래스를 제거

$(document).ready(function() {
   $("#orderedlist").find("li").each(function(i) {
     $(this).append( " BAM! " + i );
   });
 });
orderedlist 의 li 태그들을 찾아서, 각각의 li 태그 내의 값(<li>XXX</li>)에 BAM! 현재 카운트를 붙인다.
each(function(i) {...}) 에서 i 가 루프의 현재 카운트 값. 시작은 0.

$(document).ready(function() {
   // use this to reset a single form
   $("#reset").click(function() {
     $("form")[0].reset();
   });
 });

$(document).ready(function() {
   // use this to reset several forms at once
   $("#reset").click(function() {
     $("form").each(function() {
       this.reset();
     });
   });
 });
폼 리셋하기.
위는 폼이 1개일 때. 밑은 여러 개일 때.

$(document).ready(function() {
   $("li").not(":has(ul)").css("border", "1px solid black");
 });
ul 태그를 갖지 않는 모든 li 태그에 주어진 css 스타일을 적용(border를 1px solid black으로).
원래는 모든 li 태그를 찾고 그 중에서, ul 태그를 갖는 li 태그를 제거.

$(document).ready(function() {
   $("a[name]").css("background", "#eee" );
 });
XPath 형식의 객체 선택.
name 속성을 갖는 a 태그를 선택해서 css 스타일 적용.

[jQuery] How jQuery Works

프로그래밍/Web 2009. 7. 6. 17:38 Posted by galad
출처: http://docs.jquery.com/Tutorials:How_jQuery_Works

window.onload=function() {
    alert("welcome");
}
이건 html내의 모든 것이 로드된 후에 실행되지는 않는다고.(그 이전에 실행될 듯?)

jQuery로는 다음과 같이 처리.
$(document).ready(function() {
    alert("welcome");
});

a 태그 클릭 시, 링크로 이동 전에 메시지 출력.
(a 태그에 click handler를 추가)
$(document).ready(function() {
    //alert("welcome");

    $("a").click(function(event) {
        alert("Thanks for visiting.");
    });
});

a 태그 클릭 후, a 태그의 행동을 막으려면(기본 행동을 막으려면)
$(document).ready(function() {
    //alert("welcome");

    $("a").click(function(event) {
        alert("Thanks for visiting.");
        event.preventDefault();
    });
});

기타 추가 기능
$(document).ready(function() {
    //alert("welcome");

    $("a").click(function(event) {
        alert("Thanks for visiting.");
        event.preventDefault();
        $("a").hide("slow");    // 태그 천천히 숨기기
    });

    $("a").addClass("test");        // 태그에 class 추가
    $("a").removeClass("test");    // 태그에 class 삭제
});
class는 여러 개를 추가할 수 있다.

Callback & Functions
Callback실행 전에 부모가 실행된다. Callback에 인자를 넘길 수 있다....
인자 없는 Callback
$.get('myhtmlpage.html', myCallBack);
myhtmlpage.html 실행 후, myCallBack함수를 실행한다(myCallBack은 함수 포인터).

인자 있는 Callback
$.get('myhtmlpage.html', myCallBack(param1, param2));  // 틀린 방법

$.get('myhtmlpage.html', function(){  // 올바른 방법
    myCallBack(param1, param2);
});


출처: http://www.ibm.com/developerworks/kr/library/wa-jquery1/#main
IBM에 올라오는 내용을 따라하면서 첨삭한 것임...

1. 적절하게 jQuery 함수를 호출하는 방법
 
// 틀림
<script language=JavaScript>
$("div").addClass("a");
</script>

// 바름
$(document).ready(function(){
$("div").addClass("a");
});

// - 또는 -

$(document).ready(function(){
myAddClass();
});

function myAddClass()
{
$("div").addClass("a");
}

결국
$(document).ready(function() {
    // 여기서 하라는 얘기
});

2. jQuery 체인 연결
 
$("div").addClass("a").show().text("manipulated");

3. jQuery 충돌 해결
jQuery나 다른 자바스크립트 라이브러리를 사용할 때, 서로 어울려 동작하지 않을 경우가 있다는 사실이다. 다시 말해, 라이브러리 두 개 이상을 사용할 경우, 라이브러리 둘 이상에서 변수 "$"를 사용한다면 엔진은 어떤 라이브러리가 "$" 호출을 참조해야 할지 모르는 사태가 벌어진다.이런 문제를 해결하기 위해 jQuery는 "$" 변수를 다른 변수로 사상하는 방법을 제공한다.
j$ = jQuery.noConflict();
j$("div").addClass("a");

4. 선택
모든 jQuery 루트는 페이지에서 특정 엘리먼트를 선택해 다룰 수 있는 능력이 있다. 루트에서, jQuery 선택 과정은 정말 거대한 필터 과정이다. 페이지에 존재하는 모든 엘리먼트를 명령에서 제공하는 필터에 밀어넣은 다음에, 일치하는 객체 자체나 탐색이 가능한 객체 배열을 반환한다. 첫 세 가지 예제가 가장 널리 쓰인다. HTML 태그, ID, CLASS로 객체를 찾아내는 방법이다.

(1) HTML
// 이 예제는 페이지에서 모든 <div> 태그를 보여준다. 여기서
// 처음이나 마지막에 걸리는 태그가 아니라 모든 <div> 태그를 보여줌에 주목하자.
// 배열 탐색은 이 기사 후반부에 다룬다.
$("div").show();

// 페이지에 존재하는 모든 <p> 태그에 붉은 배경색을 부여한다.
$("p").css("background", "#ff0000");

(2) ID
// 이 예제는 "sampleText"라는 id가 달린 innerHTML이나 span 엘리먼트를 찾아서 id를 "Hi"로 바꾼다.
// 명령어 처음에 나오는 "#"에 주목하자. 이는 jQuery가 사용하는 구문으로, ID를 찾는다.
// "#"은 반드시 있어야 하며, 만일 빠뜨리면 jQuery는 HTML 태그를 대신 찾으며,
// <sampleText> 태그가 페이지에 없으므로 결국 아무런 결과도 반환하지 않는다.
// 이럴 경우 아주 찾기 어려운 버그에 직면한다.

$("#sampleText").html("Hi");
페이지 디자인을 제대로 하려면 페이지에 있는 모든 ID를 유일하게 만들어야 한다. 물론 이런 규칙이 (의도적이든 의도적이지 않든) 종종 깨지긴 하지만 말이다. jQuery가 ID 선택 과정에서 첫 번째 일치하는 엘리먼트만 반환하는 이유는 적절한 페이지 디자인을 따른다고 가정하고 있기 때문이다. 동일한 페이지에 존재하는 여러 엘리먼트에 태그를 붙일 필요가 있다면 CLASS 태그가 좀 더 적절한 선택이다.

(3) CLASS
// 특정 페이지에서 "redBack"이라는 CLASS로 지정된 모든 엘리먼트 배경을 붉은색으로 만든다.
// 이 "redBack" CLASS 태그가 어떤 HTML 엘리먼트에 붙어있는지 상관하지 않음에 주목하자.
// 또한 질의 용어 앞에 붙은 .에 주목하자. CLASS 이름을 찾기 위한 jQuery 구문이다.

$(".redBack").css("background", "#ff0000");

<p class="redBack">This is a paragraph</p>
<div class="redBack">This is a big div</div>
<table class="redBack"><tr><td>Sample table</td></tr></table>
CLASS는 ID와 비슷하지만 페이지에 들어있는 엘리먼트 한 개 이상을 위해 쓰일 수 있다. 따라서 페이지에 ID당 엘리먼트 하나만 존재한다는 제약을 풀어야 한다면 페이지에 동일한 CLASS로 표시한 여러 엘리먼트를 배치할 수 있다. CLASS를 활용하면 CLASS 이름 하나만 전달하는 방식으로 페이지에 존재하는 광범위한 엘리먼트를 돌면서 함수를 실행하는 자유를 얻는다.

(4) 검색 기준 결합하기
// 모든 <p>, <span>, or <div> 태그를 가린다.
$("p, span, div").hide();

(5) 다른 필터
페이지에서 원하는 엘리먼트를 빨리 찾도록 도와주는 다른 필터도 존재한다. 이런 필터는 모두 jQuery 검색 단어에서 필터를 나타내는 ":" 글자로 시작한다. 검색 범주에서 단독으로 사용이 가능하지만, 주로 원하는 구체적인 엘리먼트를 찾기 위해 검색 기준을 튜닝하는 방식으로 앞서 소개한 세 가지 검색 기준과 함께 사용하도록 설계되었다.
// 페이지에서 모든 <p> 태그를 가린다.
$("p").hide();

// 페이지에서 HTML 태그에 무관하게 첫 엘리먼트를 가린다.
$(":first").hide();

// 검색 기준을 좀 더 정교하게 튜닝하게 다듬는 기능을 제공하기 위해 섞어서 사용하는
// 방법을 보여준다. 특정 페이지에서 첫 번째 <p> 태그만 감춘다.
$("p:first").hide();
API 페이지 참조: http://docs.jquery.com/Selectors

(6) 폼 엘리먼트 필터
추가 필터와 마찬가지로 폼 필터도 필터임을 알려주는 ":" 문자로 시작한다. 또한 검색 결과를 좀 더 정교하게 얻기 위해 다른 검색 필터와 섞어서 사용하기도 한다. 따라서 ":text"라는 검색 필터는 페이지에 존재하는 모든 텍스트 필터를 반환하며, ".largeFont:text"라는 검색 필터는 페이지에서 "largeFont" 클래스인 텍스트 필드만 반환한다. 이는 폼 엘리먼트를 정교하게 조작하기 위한 기능을 제공한다.
폼 필터는 또한 개발자가 알아 두면 좋은 내용인 엘리먼트의 개별 속성을 포함한다. 따라서 ":checked", ":disabled", ':selected"와 같은 필터는 검색 기준을 정교하게 지정하도록 사용할 수 있다.
-API 페이지 참고할 것
// class가 deleteCheck인 체크박스 중에서 체크된 것들만 선택
$(".deleteCheck:checked").each(function() {
    // Do Something
});

5. 탐색

each() 함수. 이 함수는 엘리먼트 각각을 순회하며 루프를 돌 때마다 엘리먼트를 하나씩 처리하기에 프로그래밍 측면에서 "for loop"와 동일하다. 추가적으로 "this"(일반적인 자바스크립트 구문을 사용할 경우)나 $(this)(jQuery 명령어를 사용할 경우)로 루프 내에서 각 엘리먼트를 참조할 수 있다.
// 페이지에 있는 각 <p> 태그를 대상으로 순회한다. 여기서 인라인 함수 사용에 주목하자.
// 자바에서 anonymous 클래스와 비슷한 기능이다.
// 개별 함수를 호출하거나 이와 같이 인라인 함수를 작성할 수 있다.

var increment = 1;
$("p").each(function(){

// 이제 태그를 만날 때마다 문단 카운터를 하나씩 더한다. $(this) 변수를 사용해
// 개별 문단 엘리먼트를 참조하는 방법에 주목하자.

$(this).text(increment + ". " + $(this).text());
increment++;
});

(1) 추가적인 배열 함수
// eq() 함수는 직접 배열에 속한 구성 요소를 참조할 때 사용한다.
// 이 경우 세 번째 문단(당연히 0이 시작 기준이다)을 얻은 다음에 감춘다.
$("p").eq(2).hide();

// slice() 함수는 배열에서 처음과 끝 색인을 받아서 새끼 배열을 친다.
// 다음은 페이지에서 세 번째부터 다섯 번째까지 문단을 감춘다.
$("p").slice(2,5).hide();

(2)
next() 함수
<input type=text class=validate><span></span>

function validateForm()
{
$(".validate:text").each(function(){
if ($(this).val()=="")
// 페이지에서 "validate" 클래스로 정의된 각 textfiled를 순회한다.
// 비어 있다면, <span> 바로 뒤에 오류 메시지를 집어 넣는다.

$(this).next().html("This field cannot be blank");
});
}

6.
이 기사에서 배운 내용을 하나로 합치기
웹 메일 테이블에 있는 좌상단 컬럼에 보이는 "Select All"/"Deselect All" 체크 박스에 초점을 맞춘다(아래에 강조했다). 이 체크 박스를 선택하면, 컬럼에 있는 모든 체크 박스를 선택하며, 체크 박스 선택을 해제하면, 컬럼에 있는 모든 체크 박스 선택을 해제한다.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>JQuery Test 01</title>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
   
});

function checkAll() {
    //alert($("#allCheck").attr("checked"));
    if($("#allCheck").attr("checked") == true) {
        // 체크 안 된 개별 선택을 찾아서 갯수 카운트
        var cnt = 0;
        $(".priCheck").each(function() {
            //alert($(this).val() + " : " + $(this).attr("checked"));
            if($(this).attr("checked") != true) {
                cnt++;
            }
        });

        //alert("false : " + cnt);

        // 모두 checked로
        $(".priCheck").each(function() {
            $(this).attr("checked", true);
        });
    }
    else {
        // 체크된 개별 선택을 찾아서 갯수 카운트
        var cnt = 0;
        $(".priCheck:checked").each(function() {
            //alert($(this).val() + " : " + $(this).attr("checked"));
            cnt++;
        });

        //alert("false : " + cnt);

        // 모두 unchecked로
        $(".priCheck").each(function() {
            $(this).attr("checked", false);
        });
    }
}
</script>
</head>
<body>
<table>
    <tr>
        <td><input type="checkbox" id="allCheck" onclick="checkAll();" value="AAA"></td>
        <td>전체 선택</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="1"></td>
        <td>개별 선택1</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="2"></td>
        <td>개별 선택2</td>
    </tr>
    <tr>
        <td><input type="checkbox" class="priCheck" value="3"></td>
        <td>개별 선택3</td>
    </tr>
</table>
</body>
</html>

- :unchecked와 같은 필터는 없음.
- 체크상태로 만들려면 checkbox플러그인을 쓰던가, 아님 $("XXX").attr("checked", true) 사용. attr("속성명", "값")으로 아무 속성이나 설정가능

<!-- 1 단계는 Select All 체크박스 자체 생성이다.
페이지에서 체크박스에 유일한 ID를 부여한다. -->

<input type=checkbox id=selectall>

<!-- 2 단계는 체크박스에 속한 각 행을 만들어낸다.
각 행에 속한 체크박스에 'selectable' 클래스를 지정한다. 행이 여러 개며
또한 행에 속한 각 체크박스가 동일한 행동 방식을 보이기를 원하기 때문이다. -->

<input type=checkbox class=selectable>

<!-- 3 단계(마지막)는 jQuery 코드를 사용해서 하나로 합친다. -->

// 모든 jQuery 설정 코드는 이 document.ready() 함수에 있어야 함을 기억하자.
// 아니면 올바르게 동작하기 위해 자체 함수에 포함되어 있어야 한다.

$(document).ready(function(){
// 페이지에서 selectall 체크박스를 찾기 위해 jQuery 선택 구문을 활용한다.
// (ID를 지정하는 '#'에 주목하자) 그리고 jQuery에게 selectAll() 함수를
// 누군가 체크박스에 클릭할 때마다 호출하도록 알려준다.(이벤트는 다음 기사에서
// 다루겠다).

$("#selectall").click(selectAll);
});

// 이 함수는 누군가 selectall 체크박스를 누를 때마다 호출될 것이다.
function selectAll()
{
// 이 행은 selectall 체크박스가 체크되었는지 아닌지를 판단한다.
// 다음번 기사에 소개할 attr() 함수는 넘어온 객체에서 속성을 반환한다.
// 여기서 체크 되었으면 true를, 그렇지 않으면 undefined를 반환한다.

var checked = $("#selectall").attr("checked");

// 이제 jQuery 선택 구문을 활용해서 페이지에 속한 모든 체크박스를 찾는다.
// 여기서 (각 행의 체크박스인) selectable class를 지정하는 방법을 쓴다.
// 선택 결과 넘어오는 배열을 얻어서 each() 함수를 사용해서 순회한다.
// 이렇게 되면 한번에 하나씩 결과 항목을 처리할 수 있다. each() 함수 내부에서
// $(this) 변수를 사용해서 개별 결과를 참조할 수 있다. 따라서 루프 내부에서
// 각 체크박스 값을 찾아서 selectall 체크박스와 일치하도록 만든다.

$(".selectable").each(function(){
var subChecked = $(this).attr("checked");
if (subChecked != checked)
$(this).click();
});
}


[jQuery] select option

프로그래밍/Web 2009. 5. 14. 14:03 Posted by galad
출처: http://www.texotela.co.uk/code/jquery/select/

        // 이메일
        $("#email_select").selectOptions("${email_select}");
        $("#email2").val("${email2}");
        // 생일
        $("#birth1").selectOptions("${birth1}");
        $("#birth2").selectOptions("${birth2}");
        $("#birth3").selectOptions("${birth3}");

좋군...

[펌] Ajax, jQuery 관련 강의

프로그래밍/Web 2009. 2. 6. 13:23 Posted by galad