'팁&테크/jQuery'에 해당되는 글 10건

  1. 2021.05.12 [jQuery] 버전 별 autocomplete _renderItem 차이
  2. 2020.01.09 [jQueryUI Tab] Page Refresh 후에도 Tab이 변하지 않는 방법
  3. 2019.12.26 [Jquery] Textarea 높이 자동
  4. 2018.07.16 엘리먼트 역순으로 each하기 (element reverse order)
  5. 2018.07.05 jQuery.validity Guide & Documentation
  6. 2017.06.23 jquery validate ajax form submit 2가지 방법
  7. 2012.01.04 JQuery UI position 유틸리티 1
  8. 2011.12.15 fancybox api
  9. 2011.12.09 jquery 관련 (메모)
  10. 2010.11.03 Jquery SELECT 태그 관련 내용 1
2021. 5. 12. 13:22

[jQuery] 버전 별 autocomplete _renderItem 차이

JQuery-ui 버전에 따라 autocomplete 사용법이 다름.

 

[1.12.0]

jquery 1.7.x 버전 이상을 써야 하고 최신버전 3.2.1 에서도 동작한다.

.autocomplete( "instance" )._renderItem 을 사용할 수 있고

.data("ui-autocomplete")._renderItem 을 사용할 수도 있지만 old style

 

.autocomplete( "instance" )._renderItem = function( ul, item ) {

    return $( "<li>" ).append( "<div>" + gubun + S9HL.highlight(label, searched) + "</div>" ).appendTo( ul );

)};

 

[1.11.x]

jquery 1.6.x ~ jquery 2.x 버전까지 동작

.autocomplete( "instance" )._renderItem 을 사용할 수 있고

.data("ui-autocomplete")._renderItem 을 사용할 수도 있지만 old style

 

.autocomplete( "instance" )._renderItem = function( ul, item ) {

    return $( "<li>" ).append( "<div>" + gubun + S9HL.highlight(label, searched) + "</div>" ).appendTo( ul );

혹은

    return $( "<li>" ).append(gubun + S9HL.highlight(label, searched)).appendTo( ul );

)};

 

값을 <div> 혹은 <a> 둘 다 동작하는 것으로 보이지만 <div> 가 더 좋다

<div>를 쓰지 않아도 동작한다.

[1.8.x]

jquery 1.7 버전 이상을 쓸 수 없다 (deplicate 된 함수 때문이다)

.data("ui-autocomplete")._renderItem 을 사용해야 한다.

 

.data("autocomplete")._renderItem = function(ul, item ) {

    return $( "<li>" ).data( "item.autocomplete", item ).append( '<a>' + S9HL.highlight(item.label, searchQuery) + '</a>' ).appendTo( ul );

};

값은 반드시 <a> 로 싸야 한다.

2020. 1. 9. 10:14

[jQueryUI Tab] Page Refresh 후에도 Tab이 변하지 않는 방법

var currentTab = window.location.hash.substring(1);
var tabIndex = ["RequiredDocuments", "AdditionalDocuments"];
$( "#tabs" ).tabs({
    create: function(event, ui) {
        var index = ui.tab.index();
        window.location.hash = tabIndex[index];
    },
    activate: function(event, ui) {
        var index = ui.newTab.index();
        window.location.hash = tabIndex[index];
    },
    active: currentTab.length !== 0 && tabIndex.hasOwnProperty(currentTab) ? tabIndex.indexOf(currentTab) : 0
});

구버전은 아래처럼.

var currentTab = window.location.hash.substring(1);
var tabIndex = ["RequiredDocuments", "AdditionalDocuments"];
$("#tabs").tabs({
    show: function(event, ui) {
        window.location.hash = tabIndex[ui.index];
    },
    selected: currentTab.length !== 0 && tabIndex.hasOwnProperty(currentTab) ? tabIndex.indexOf(currentTab) : 0
});

 

2019. 12. 26. 09:02

[Jquery] Textarea 높이 자동

$("textarea").each(function() {
var offset = this.offsetHeight - this.clientHeight;
var resizeTextarea = function(el) {
$(el).css('height', 'auto').css('height', el.scrollHeight + offset);
};
$(this).on('keyup input focusin', function() { resizeTextarea(this); });
});


2018. 7. 16. 09:28

엘리먼트 역순으로 each하기 (element reverse order)

$($('selector').get().reverse()).each(function() {
    //내용
});
2018. 7. 5. 16:02

jQuery.validity Guide & Documentation

어느날 들어가보니 다른 나라에서 접속하는걸 차단하길래 일단 저장해놓음

jQuery.validity Guide & Documentation


Table of Contents:


Introduction:

jQuery.validity is a plugin designed to aid in the configuration of clientside form-validation. Validity was concieved with three goals:

  1. Easy Setup: Validity employs the principle of Convention Over Configuration to aid in keeping code manageable and semantic. Very little work is required to enable Validity for a page.
  2. Unobtrusive JavaScript: Using Validity will have little to no effect on the semantics of your markup. Additionally, Validity will degrade gracefully and leave no residuals in browser environments where JavaScript is disabled or unsupported.
  3. Customizable Appearence: Validity is an effort to deliver a solid core-library of validation tools that can be used in any web-design. Therefore, in order to be truly versatile, validation logic is separated from the way it displays errors. With Validity, you, the developer, have full control of error message handling and adapting it to the design of your page.

In style, validity makes use of jQuery's selector engine and follows its pattern of method chaining. If you know jQuery, then learning to use validity will be easy.


Setup:

In order to use Validity on a page, you will need to import the jQuery JavaScript library as well as jQuery.validity itself. Additionally, you will need to import the CSS styles for the error handling.

As a simple example suppose we start with the following HTML document with a simple form:

<html>
    <head>
        <title>Simple</title>
    </head>
    <body>
        <form method="get" action="simple.htm">
            Number of Vehicles:
            <input type="text" id="vehicles" name="vehicles" title="Vehicle Count" />
            <br /><br />
            Date of birth:
            <input type="text" id="dob" name="dob" title="Birthday" />
            <br /><br />
            <input type="submit" />
        </form>
    </body>
</html>
            

As you can see, there is no validation logic attached to the form. To import Validity we add the following code to the document's head.

<link type="text/css" rel="Stylesheet" href="jquery.validity.css" />

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.validity.js"></script>

<script type="text/javascript">
    // Select all of the forms on the page (in this case the only one)
    // and call 'validity' on the result.
    $(function() { 
        $("form").validity(function() {
            
        });
    });
</script>
            

Once jQuery, jQuery.validity and the validity styles are imported we can specify the validation logic using the validity method. Normally, this the validity method is called on jQuery objects of HTML forms and accepts a function as argument. As you can see, in the code above, a jQuery selector finds the form and then the validity method is called with an empty anonymous function as argument.

Inside the function argument we can specify the validation code.

Let's say that we want to require both of the fields. Also, we want to restrict the first field to be in the form of a number between 4 and 12. The second field will need to be a date and that date will have to be at some point in the past.

Validation methods are covered in greater detail later on in this document, but for now we can specify validation with the following use of the 'validity' method.

$("form").validity(function() {
    $("#vehicles")                      // The first input:    
        .require()                          // Required:
        .match("number")                    // In the format of a number:
        .range(4, 12);                      // Between 4 and 12 (inclusively):
    
    $("#dob")                           // The second input:
        .require()                          // Required:
        .match("date")                      // In the format of a date:
        .lessThanOrEqualTo(new Date());     // In the past (less than or equal to today):
});
            

That's all of the code that needs to be written to have a form validated by validity. Putting it all together, the interactive example below is produced.

<html>
    <head>
        <title>Simple</title>
        <link type="text/css" rel="Stylesheet" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"> </script>
        <script type="text/javascript" src="../../jquery.validity.js"> </script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity(function() {
                    $("#vehicles")
                        .require()
                        .match("number")
                        .range(4, 12);
                    
                    $("#dob")
                        .require()
                        .match("date")
                        .lessThanOrEqualTo(new Date());
                });
            });
        </script>
    </head>
    <body>
        <form method="get" action="simple.htm">
            Number of Vehicles:
            <input type="text" id="vehicles" name="vehicles" title="Vehicle Count" />
            <br /><br />
            Date of birth:
            <input type="text" id="dob" name="dob" title="Birthday" />
            <br /><br />
            <input type="submit" />
        </form>
    </body>
</html>
                

Note: As of versiom 1.0.2+ you'll also need to put the arrow.gif image in the same directory as the stylesheet. (Otherwise the label output mode will not render correctly. See Label Output Mode Styles.)


Assigning Validation:

There are multiple ways to assign validation logic to a form.

  • In the Setup example the validity method is used with a function argument. For example:

    // The validity method is being called on the form.
    $("form").validity(function() {
    
        // This function is being passed into the validity method.
        // Validation logic can go here.
        
    });
                            

    More on this technique below under Using a Function Argument.

  • The validity method can also be called with a string argument. For example:

    // The validity method is being called on the form with a string argument.
    $("form").validity("input:text, select");
                            

    More on this technique below under Using a String Argument.

  • Furthermore, validity can be used without the validity method, for instance, when validating Ajax.

    More on this technique below under Using Validity with Ajax.


The Validity Method

The validity method is defined on all jQuery objects, however it will only effect form elements. You may use it to select one or more forms and register the validation for each. There are two argument types that the method will accept: a function and a string.


Using a Function Argument

In almost all cases your argument into the validity method will be a function. Within the function you will call the validator methods.

The advantage of using a function argument for validation lies in your access to the jQuery selector engine for specifying rules.

For Advanced Users: the other advantage to function arguments is your ability to use JavaScript control structures (such as if...else blocks, iterators, etc.). In other words, the function passed into the validity method is executed just like any other JavaScript function. If your validation rules are conditional, nonlinear or otherwise complicated you can write whatever logic you need to. An example of a conditional validation scenario is below with the checkbox.


Basics

A simple validation scenario allows you to simply select individual inputs and setup validation on each. For example:

$('#my-form').validity(function() {

    // Required and has to be a number.
    $("#text-box-one")
        .require()
        .match("number");
    
    // Not required, but it has to be a date
    $("#text-box-two")
        .match("date");
        
});
            

You may also take advantage of the selector engine and validate several inputs with a single statement. For instance, if a page has several inputs that need to represent percentages, and that all need to add up to 100%, then the following code may be appropriate.

$('#my-other-form').validity(function() {

    // All of the interesting inputs will be under a percentage class, so:
    $(".percentage")
        .require()          // Each is required 
        .match("number")    // Each must be numeric
        .sum(100);          // The sum of all of them should be 100%.
        
});
            

Furthermore, you can use JavaScript control structures to conditionally validate. In the following interactive example, an if...then structure is used to require an email input only if the checkbox is checked.

<html>
    <head>
        <title>Conditional</title>
        <link rel="Stylesheet" type="text/css" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"></script>
        <script type="text/javascript" src="../../jquery.validity.js"></script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity(function() { 
                    if ($("#maillist").attr("checked")) {
                        $("#email")
                            .require("We'll need #{field} if you want to be on the mailing list.")
                            .match("email");
                    }
                });
            });
        </script>
    </head>
    <body>
        <form action="conditional.htm" method="get">
            <input type="checkbox" id="maillist" name="maillist" />
            
            <label for="maillist">
                Yes, I'd like to recieve updates: 
            </label>
            
            <br />
            
            <label for="email">
                My email:
            </label>
            
            <input type="text" id="email" name="email" title="your address" />
            
            <br />
            
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                

This is an example of using JavaScript control structures in the validity method.


Understanding Chains

You may have noticed that the validator functions can be called on the results of other validator methods in the manner of jQuery function chaining. For instance:

// Selector:       1st:      2nd:            3rd:         Chain ends:
$("#some_textbox").require().match("number").range(24, 64);
            

The basic mechanism involved with chains is that functions later in a chain will only do validation if the previous ones succeed.

In other words, in the above code snippet, if the input does not have a value (i.e. require() fails and raises an error) then validity is smart enough to not check the format when it gets to match("number"). It would be meaningless to complain about the format if there was no value to check.

In this fashion you can assign the validator methods in the order of most essential first, and then do the more specific rules later in the chain.

Requiring a value is more essentiall than restricting it to the format of a number. Restricting its format is more essential than checking its range.


Using a String Argument

If you only need to require some of the inputs, and you don't need to format-check them, you can simply pass a string into the validity method.

The string needs to be a jQuery selector expression that would select the elements you wish to validate.

In the following interactive example, we validate the page with the statement:

$("form").validity("input:text, select"); 
            

This is because the string argument would select all of the inputs we need.

<html>
    <head>
        <title>String Argument</title>
        <link type="text/css" rel="Stylesheet" href="../../jquery.validity.css" />
        <script type="text/javascript" src="../../jquery.js"></script>
        <script type="text/javascript" src="../../jquery.validity.js"></script>
        <script type="text/javascript">
            $(function() { 
                $("form").validity("input:text, select");
            });
        </script>
    </head>
    <body>
        <form method="get" action="stringargument.htm">
            <label for="PetName">Name of Pet:</label>
            <input type="text" id="PetName" name="PetName" title="name" />
            <br /><br />
            
            <label for="PetType">Type of Pet:</label>
            <select id="PetType" name="PetType" title="type">
                <option selected="selected"></option>
                <option>Dog</option>
                <option>Cat</option>
                <option>Bird</option>
                <option>Lizard</option>
                <option>Panda</option>
            </select>
            <br /><br />
            
            <label for="Petfoodbrand">Brand of Petfood:</label>
            <input type="text" id="Petfoodbrand" name="Petfoodbrand" title="brand" />
            <br /><br />
            
            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
                

If we wished to make the petfood input optional, we could modify the string the same way we'd craft a jQuery selector to exclude this input. For example:

$("form").validity("input:text:not(#Petfoodbrand), select");
            

Using Validity with Ajax

If your page uses Ajax and cannot bind to a form in the way described above, or you otherwise wish not to use the validity method, you will need to manually call validity's start and end functions.

$.validity.start();

// And:

var result = $.validity.end();
            

These functions are really quite easy to use.

Essentially, the start function should be called before any validator methods. The end function should be called after all the validator methods have been called, and it returns an object representing the results of the validation.

The result object that is returned by the end function bears two properties: valid and errors.

  • valid is a boolean representing whether no errors occurred between the times that start and end were called. If there were no errors, valid will be 'true'.
  • errors is an integer representing how many errors occurred. If valid is 'true' then errors will be '0'.

For example, some code that would validate inputs without a form might look like this:

// This is the validation function:
function validateMyAjaxInputs() {

    // Start validation:
    $.validity.start();
    
    // Validator methods go here:
    
    // For instance:
    $("#my_textbox").require();
    
    // etc.
    
    // All of the validator methods have been called:
    // End the validation session:
    var result = $.validity.end();
    
    // Return whether it's okay to proceed with the Ajax:
    return result.valid;
}


// This is the function wired into the click event of some link or button:
function ajaxButtonClicked() {

    // First check whether the inputs are valid:
    if (validateMyAjaxInputs()) {
    
        // Do ajax:
        // ...
        
    }
}
            

Validators

Validity defines various methods onto jQuery objects for validation. We'll call these validator methods.


Common Validators

The common validator methods all deal specifically with individual inputs. Any of them can be called on jQuery objects of several inputs. Each input will be validated indivdiually.

In other words, we could use jQuery several times to select each input and call the 'require' validator method each time. Alternatively, and more elegantly, we could simply select all of the needed inputs and call 'require' once on that.

// For example:

// Wirting:
$('#input-1').require();
$('#input-2').require();
$('#input-3').require();
$('#input-4').require();
$('#input-5').require();

// Would be equivalent to:
$("#input-1, #input-2, #input-3, #input-4, #input-5").require();

// Or, if there are no other inputs than these five:
$("input").require();

// The power is in the selector.
            

Below are summarized the various common validator methods.


Require:

Signature:
jQuery("selector").require( ['message'] )
Arguments:
  • message: An optional message to display if an element fails.
Overview:

This is the most basic validation method. It merely checks to ensure that inputs have values. If any do not have a value (i.e. value.length is zero) an error is raised for that input and the form should not be submitted.

Examples:
// Require all inputs, use the default error message.
$("input:text").require();
            
// A specific error message is attached to a specific input.
$("#ssn").require("Your Social Security Number is required to proceed.");
            

Match:

Signature:
jQuery("selector").match( 'patternName'|RegExp, ['message'] )
Arguments:
  • patternName: A named pattern to match against. A list of the named formats that are built into validity can be found below.
  • RegExp: Instead of a named pattern, you may enter a RegExp object to use for testing the value.
  • message: An optional message to display if an element fails.
Overview:

Tests that the inputs conform to the specified format. This is achieved by passing in a Regexp to match the value against. validity also includes several common Regexps that you may use by merely passing in their name as a string.

The built-in Regexp names are:

integer
Will match only positive, whole numbers.
date
Will only match dates in the American mm/dd/yyyy format. To support other date formats refer to the Internationalization Section later on in this document.
email
Matches email addresses.
usd
Matches U.S. Dollar amounts.
url
Matches web-addresses.
number
Matches a number. It could be an integer or float, positive or negative or in scientific-notation.
zip
Matches an U.S. Postal Code (in both 5 and 9 digit forms).
phone
Matches an U.S. Domestic Phone number.
guid
Matches a globally unique identifier. Should be formatted such as
{3F2504E0-4F89-11D3-9A0C-0305E82C3301}
time12
Matches a time in 12-hour format.
time24
Matches a time in 24-hour format.
Examples:
// Make sure that all inputs under the 'date' class are 
// properly formatted. (Given they bear a value.) If any 
// fail, they will be tagged with a default error message 
// associated with the 'date' pattern.
$('input.date').match('date');
            
// Same as the previous example, but the dates are now required also.
$('input.date')
    .require()
    .match('date');
            
// Ensures that an input named 'employeeId' conforms to a 
// special, company-specific pattern, and specifies a 
// helpful message.
$('#employeeId').match(/^\d{2}[-]\d{4}$/, "Employee Ids must be in the form XX-XXXX.");
            
// Same as the previous example, but the message is tokenized:
$('#employeeId').match(/^\d{2}[-]\d{4}$/, "#{field} must be in the form XX-XXXX.");
            

Range:

Signature:
jQuery("selector").range( min, max, ['message'] )
Arguments:
  • min: The inclusive lower-bound for valid values.
  • max: The inclusive upper-bound for valid values.
  • message: An optional message to display if an element fails.
Overview:

Will restrict the value to an inclusive numeric or date range. The min and max arguments should be either both numbers or both JavaScript date objects.

Since the range validator expects either numbers or dates you should use range after a match validator so that you may be sure that the values which are range-checked will be in a valid format.

Examples:
// Restrict valid values to an inclusive numeric range.
$("#percentage")
    .match(/^\d+\.?\d*%?/, "Must be formatted like a percent.")
    .range(0, 100);
            
// Restrict valid values to an inclusive temporal range.
$("#DayDuringClintonAdministration")
    .match('date')
    .range(new Date("01/20/1993"), new Date("01/20/2001"));
            

Greater Than/Greater Than or Equal To:

Signature:
jQuery("selector").greaterThan( min, ['message'] )
jQuery("selector").greaterThanOrEqualTo( min, ['message'] )
Arguments:
  • min: The lower-bound for valid values.
  • message: An optional message to display if an element fails.
Overview:

Restricts the value to be larger than the specified minimum.

Since the greaterThan/greaterThanOrEqualTo validator expects either numbers or dates you should use it after a match validator so that you may be sure that the values which are checked will be in a valid format.

Examples:
// Validates a cost input, that it must be more than zero.
$("#cost")
    .match("usd")
    .greaterThan(0);
            
// Validates a velocity input, that it must be greater than or equal to zero.
$("#velocity")
    .match("number")
    .greaterThanOrEqualTo(0, "You cannot have negative velocity.");
            

Less Than/Less Than or Equal To:

Signature:
jQuery("selector").lessThan( max, ['message'] )
jQuery("selector").lessThanOrEqualTo( max, ['message'] )
Arguments:
  • max: The upper-bound for valid values.
  • message: An optional message to display if an element fails.
Overview:

Restricts the value to be smaller than the specified minimum.

Since the lessThan/lessThanOrEqualTo validator expects either numbers or dates you should use it after a match validator so that you may be sure that the values which are checked will be in a valid format.

Examples:
// Validates an angle input, that it must be less than 180.
$("#angle")
    .match("number")
    .lessThan(180);
            
// Validates a hours input, that it must be less than or equal to 24.
$("#HoursPerDay")
    .match("integer")
    .lessThanOrEqualTo(24, "#{field} cannot be more than #{max}.");
    
// The resulting tokenized message could be "Hours Per Day cannot be more than 24."
            

Max Length/Min Length:

Signature:
jQuery("selector").maxLength( max, ['message'] )
jQuery("selector").minLength( min, ['message'] )
Arguments:
  • max: The upper-bound for the length of valid values.
  • min: The lower-bound for the length of valid values.
  • message: An optional message to display if an element fails.
Overview:

Restricts the length of the value to the specified maximum or minimum. This validator is useful to restrict input values to the max-length allowed by a database schema.

Examples:
// Limit the length of a value to be less than 255:
$("textarea#description").maxLength(255);
            
// Specify a minimum length for the value:
$("#detailedExplaination")
    .minLength(1000, "You need to give more detail.");
            

Non HTML:

Signature:
jQuery("selector").nonHtml( ['message'] )
Arguments:
  • message: An optional message to display if an element fails.
Overview:

Disallows the angle brackets necessary for XSS attacks.

Examples:
// Disallow HTML in the specified input:
$("#myBiography").nonHtml();
            

Aggregate Validators

Aggregate validators are able to do validation rules that involve more than one input. In a similar way to how aggregate functions in SQL take several records and gather them into one result, aggregate validators can take several HTML elements and determine whether they are valid with regard to eachother.

This feature of validity takes advantage of the jQuery selection engine to gather multiple results.


Equal:

Signature:
jQuery("selector").equal( [transform], ['message'] )
Arguments:
  • transform: Optional transform function to apply to each value before testing.
  • message: An optional message to display if an element fails.
Overview:

Ensure that the values of all matched elements are equal to each other. This is an aggregate validator, meaning that it should be applied to groups of inputs.

A common use for the equal validator is in password-confirmation scenarios, where a form should not be submitted if a user fails to reenter his or her password correctly.

Examples:
// Write a jQuery selector that results in both the password and its confirmation,
// make sure that they conform to your password conditions with the match validator,
// then validate that result with 'equal'.
$("text[type='password']")
    .match(mySpecialPasswordRegex, myPasswordFormatMessage)
    .equal("Passwords do not match.");
            
// We can also extract the important part of a value, and test the equality only on that.
// For instance, we might want phone numbers to be equal disregarding whether they
// use '.' or '-' to separate groups, or have the area code in parentheses.
$("input.phone")
    .match("phone")
    .equal(
        function(val) { 
            return val.replace(/[-.()]/, '');
        },
        "All phone numbers must be the same."
    );
            

Distinct:

Signature:
jQuery("selector").distinct( [transform], ['message'] )
Arguments:
  • transform: Optional transform function to apply to each value before testing.
  • message: An optional message to display if an element fails.
Overview:

Ensures that the values of all matched elements are distinct from each other. In other words, validate that no value is repeated among the matched elements.

If any of the matched elements do not have a value that element will not be tested. Consequently, the distinct validator will work with inputs that are or are not required.

Examples:
// Find all the inputs meant to hold Vehicle Identification Numbers.
// Since every VIN should be different, a repeat should be treated as invaid.
$("input.vin").distinct("A VIN Number was repeated.");
            
// We can also use a transform to normalize values.
// For instance, if we wish to ignore case 
// (i.e. if "abc" and "ABC" should be treated as a repeat)
// we can pass in a transform that makes all values upper-case.
// An example of this might be network interface hardware addresses.

// We'll allow the values to be in upper or lower case, 
// but treat those as the same value.
$("input.macAddress")
    .match(/([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}/, "Must be a valid MAC address.")
    .distinct(
        function(val) { 
            return val.toUpperCase();
        },
        "A hardware address was repeated."
    );
            

Sum/Sum Max/Sum Min:

Signature:
jQuery("selector").sum( sum, ['message'] )
jQuery("selector").sumMax( max, ['message'] )
jQuery("selector").sumMin( min, ['message'] )
Arguments:
  • sum: The value that the sum of matched elements should be equal to.
  • max: The inclusive upper-bound for the sum of matched elements
  • min: The inclusive lower-bound for the sum of matched elements
  • message: An optional message to display if an element fails.
Overview:

Validate that the numeric sum of the value of all matched elements is equal to a given value or bounded by a specified max or min. If any value is not parseable as a number it will be ignored.

Examples:
// Find inputs representing the three interior angles of a triangle.
$("input.triangleAngle")
  .require()
  .match("number")
  .sum(180, "A triangle's angles should add up to 180 degrees.");
            
// Find inputs representing the how you intend to distribute 100,000 dollars among
// several people without having to distribute all of it.
$("input.distribution")
  .match("usd")
  .sumMax(100000, "You can't distribute more than you have on hand.");
            

Specialized Validation:

Validity supplies validator methods that cover the most common scenarios, but it also offers a tool to write your own custom validator with assert.

assert is at once the most complicated and most capable validator in the validity suite. It's use is thoroughly outlined below.


Assert:

Signature:
jQuery("selector").assert( expression|function, ['message'] )
Arguments:
  • expression: Any expression that will result in a boolean. When expression evaluates to true the validator succeeds. Keep in mind, when passing an expression rather than a function, assert will act like an aggregate validator. That is to say, the truth or falsehood of expression will determine the validity of ALL matched elements.
  • function: A javascript function object which will accept a DOM Element and return true or false representing whether that DOM element was valid. Keep in mind that when passing a function rather than an expression assert will act like a common (non-aggregate) validator. That is to say that the function will be applied to each and every matched element and their validity is determined individually.
  • message: An optional message to display if an element fails. While this argument is optional, it is strongly encouraged for use with the assert validator.
Overview:

Assert allows you to validate inputs using your own customized logic, but still let validity display the error messages. If what you need is not provided among validity's built-in validator methods, you can write it yourself with assert. (In fact, any of the built in functions could be replicated with assert. It's that powerful.)

There are two general ways to use assert: you can pass in an expression argument (which evaluates into a boolean), or you can pass in a JavaScript function object. It is important to understand that assert will act like an aggregate validator when an expression is passed, but will act like a common (non-aggregate) validator when a function object is passed.

Examples:

To illustrate these techniques, we can write a validator to determine whether a set of inputs are all evens or all odds:

$(function() {
    $("form").validity(function() {
        // Store the information in local variables:
        // These are booleans:
        var allEvens = (
            parseFloat($("#box1").val()) % 2 == 0 &&
            parseFloat($("#box2").val()) % 2 == 0 &&
            parseFloat($("#box3").val()) % 2 == 0 &&
            parseFloat($("#box4").val()) % 2 == 0
        );
        var allOdds = (
            parseFloat($("#box1").val()) % 2 == 1 &&
            parseFloat($("#box2").val()) % 2 == 1 &&
            parseFloat($("#box3").val()) % 2 == 1 &&
            parseFloat($("#box4").val()) % 2 == 1
        );
        
        // Pass the OR of those two booleans as the expression argument into assert.
        // This will cause the inputs to be considered all valid or all invalid.
        $("#box1, #box2, #box3, #box4")
            .match("integer")
            .assert(
                (allEvens || allOdds), 
                "The inputs can either have all even numbers or all odd numbers. Not mixed."
            );
    });
});
            

As another example, we can pass a function object to perform common, non-aggregate validation. In the below example we can individually determine whether any of the selected inputs is a palindrome:

// First create the functions that will be used in validation.
        
// Helper to reverse a string:
function reverse(s){
    var  r = "";
    var  l = s.length;
    for (var i = l; i > 0; i--){
        r += s.charAt(i-1);
    }
    return r;
}

// Returns whether the value of the passed element is a palindrome:
// Notice that this function is meant to accept the DOM element, 
// not the value of the DOM element.
function isPalindrome(element){
    return element.value == reverse(element.value);
}
            
$(function() {
    $("form").validity(function() {
        // Instruct assert to use this function to test each input.
        // Notice that we're passing the function itself 
        // rather than the result of the function.
        // (i.e. "isPalindrome" not "isPalindrome()" )
        $(":text").assert(
            isPalindrome, 
            "#{field} must be a palindrome."
        );
    });
});
            

Tokenized Messages

Validity will attempt to generate helpful error messages based on how you validate what inputs. This feature is intended to minimize the number of error messages you'll be required to write yourself and to keep validation messages consistent.

Note: Validity will still grant you full control over the messages. You will not be forced to use this feature, although it can be used to simplify your code.


Understanding Tokenized Messages

The mechanism validity uses to generate these messages is a library of default message strings that contain tokens. For example, validity contains the following string as a default message for required field errors:

"#{field} is required."
            

The #{field} part at the beginning of the string is a token to be replaced with the title of the input for which the error is being created. In this way, a required field error being generated for an input titled "your name" will generate the message "Your name is required."

Similary, the tokenized message for range validators is:

"#{field} must be between #{min} and #{max}."
            

As you can see, there are tokens for the min and the max so that those values can be inserted into the error message. An example result message might be: "Age of car must be between 10 and 60."

Because every validator method allows you to pass in your own validation message to override the default, you may use tokens when you do this. For instance, if you use the match validator with your own regular expression to validate multiple inputs you might use a tokenized message in the following way:

$("input.ssn").match(
    /^\d{3}-\d{2}-\d{4}$/, 
    "#{field} needs to be in the format of a Social Security Number."
);
            

In this way you can have validity generate several messages for each input. The above statement might generate the error messages: "Your SSN needs to be in the format of a Social Security Number.", "Cosigner A SSN needs to be in the format of a Social Security Number.", and "Cosigner B SSN needs to be in the format of a Social Security Number."

Note: All default messages can be rewritten or modified to fit the parlance of your site. For information on how to do this refer to the Customizing Messages section later on in this document.


Best Practices

A significant part of how Validity generates error messages involves figuring out what the name of the input should be. Validity needs to guess the name of an input in order to insert that into the #{field} token of a tokenized message. It is important to understand how Validity makes this guess in order that you can help it to guess correctly.

  1. Validity will first look at the "title" attribute of an input. If an input has a title attribute Validity will assume that is its name. For example, if validity had to guess the name of the following input it will assume that it's "User Name" because that is the value of the title attribute.

    <input id="not_helpful" name="not_helpful" title="User Name" />
                        

    Using the title attribute in this way is the preferrable method. If you're able to set the title attribute of an input, you're advised to do so this way.

  2. Validity will next look at the "id" attribute of the element. If the id attribute appears to be in "Upper Camel Case" format (sometimes called Pascal Case) it will take that value and split it into words by inserting a space before each capital letter.

    For example, if Validity had to guess the name of the following input, it will assume that it's "User Name" because the value of the id attribute is in Upper Camel Case form and there is no "title" attribute.

    <input id="UserName" name="UserName" />
                        
  3. If the previous two checks have failed, Validity will check whether the id is in the form of lower-case words separated by underscores. If Validity finds this format, it will replace each underscore with a space and capitalize the first letter of each word.

    For example, Validity would assume the that name for the following input is "User Name".

    <input id="user_name" name="user_name" />
                        
  4. If Validity has failed the previous three tests, it will use a default field name which is built-in. This default name is:

    defaultFieldName: "This field"
                        

    Often, if Validity ends up using the default field name, the error messages will still be helpful and natural-looking because, with the label and modal output modes at least, error messages are positioned right next to the input to which they refer.

  5. Lastly, if you are not able to set the title attribute or do not have the ability to give your inputs meaningful ids and you don't wish the default field name to be used, you can always pass a specific non-tokenized string of your message into the validator call. Each and every validator will accept a string as its last argument to be used as the message.


Output Modes

Although Validity is able to validate inputs, its other role is to display errors appropriately and consistently. The logic that Validity uses to display errors is wrapped up into what's called an output mode. There are three output modes included with validity, each of which are summarized in the following sections.

You are also able to write your own output mode and get full control to how messages are displayed. For a full explanation of how to do this see the Writing a Custom Output Mode section later in this document.

You may instruct Validity which output mode you would like to use using the setup function. For example, to enable the "summary" output mode, the following code would be appropriate:

$.validity.setup({ outputMode:"summary" });
            

Label

Label is the default output mode in Validity. If you do not specify another output mode using the setup function, label will be what is used.

When this output mode creates an error message, it will create an HTML label element with the CSS class "error", the "for" attribute set to the id of the input it is being created for and the text of the error message. This label element is then positioned after the input it has been created for.

The advantage of this output mode is that it will place error messages very helpfully next to the offending inputs. Additionally, it does not require anything to be setup in advance (aside from the styles in the CSS file).

Although it's default, you would be able to enable the label output mode with the code:

$.validity.setup({ outputMode:"label" });
            

The Modal output mode acts similarly to Label - however, instead of inserting the error message into the HTML next to the input, it will position the message so that it hovers near the input.

In this way, using the Modal output mode will not mess up the layout of your site. Modal is very useful in web-designs involving tightly-knit tables or small areas.

You can enable the modal output mode with the code:

$.validity.setup({ outputMode:"modal" });
            

By default, modal error messages will disappear when they've been clicked. This behavior can be disabled with the following code:

$.validity.setup({ modalErrorsClickable:false });
            

Summary

The Summary output mode behaves quite differently from Label or Modal. Summary will gather all of the validation messages and compile them into a summary to be displayed when validation has concluded. Instead of placing the messages next to the inputs, it will highlight the input and the message will appear in the summary.

This is very useful in web pages with long forms to fill out, where it's important to keep the look clean and professional.

Also unlike Label and Modal, the Summary output mode requires a small amount of markup in order to operate. You will need to insert the following code wherever you want the summary of messages to appear:

<div class="validity-summary-container">
    Here's a summary of the validation failures:
    <ul></ul>
</div>
            

The text in this code snippet ("Here's a summary of the validation failures:") is a message that is meant to explain that it's part of a summary of validation errors. This message will not be shown if there are no errors. You are encouraged to edit this message as you see fit.

Essentially, the element with CSS class of validity-summary-container is shown or hidden depending whether there are any errors. The actual messages will be insterted into their individual <li/> elements into the <ul/> element inside of the container element.

You can enable the summary output mode with the code:

$.validity.setup({ outputMode:"summary" });
            

Customizing Validity Itself

Architectually, Validity is written along the programming principle of Separation of Concerns. In this way, Validity is able to allow developers to customize and replace components simply and safely. Here we summarize and guide through the different ways Validity can be modified.


Adapting the CSS

The simplest way to modify Validity is to adapt the CSS to the look of your site. As much as possible, Validity lets CSS decide how things look so that it can be safely modified without forcing you to hack JavaScript.

Validity comes with a boilerplate CSS file (jquery.validity.css). You may simply include this file on your site as a stylesheet reference, but are encouraged to copy and paste the styles from it into your own CSS file where you can edit them freely.

The CSS file contains three groups of styles. (One for each of the output modes. See Output Modes.) The groups you decide to copy over and modify should depend on which Output Modes you are using.


Label

The Label output mode uses a single style. The selector for this style is label.error, therefore it will be applied to all HTML label elements with the CSS class error.

The boilerplate CSS for this style is nothing special. It specifies some colors and a background image that grants the label an arrow-shaped corner on the left side. It also makes use of unstandardized properties that give the labels rounded corners in non-Internet-Explorer browsers. Below is an example:

This is a validation message.

The complete CSS style for the Label output mode is below:

label.error { 
    color:#fff; 
    margin-left:2px;     
    background-image:url('arrow.gif');
    background-position:left center;
    background-repeat:no-repeat;
    padding:2px;
    padding-left:18px;
    -moz-border-radius:4px;
    -webkit-border-radius: 4px;
}
            

To adapt the look of the label output mode, this style is all that must be changed.


Modal

The Modal output mode uses two styles by default. These styles are built around the validity-modal-msg CSS class. When Validity generates a Modal message, it will be placed under this class.

For the most part these styles determine the appearence of the messages (i.e. Background Color, Border, Padding, etc.), but it is important to note the position:absolute; statement. This property is necessary for the Modal errors to be positioned near the inputs. If you edit this style, do not change the position property.

The other style used by Modal is an hover pseudoclass that highlights the error messages to indicate that they might be clicked. If you disable the modalErrorsClickable setting (see Modal) you may wish to remove this style.

Below is an example:

This is a validation message.

The complete CSS styles for the Modal output mode are below:

.validity-modal-msg { 
    position:absolute; 
    z-index:2; 
    background-color:#999; 
    border:solid 1px #000; 
    padding:4px;
    cursor:pointer; 
}

.validity-modal-msg:hover { 
    background-color:#aaa; 
}
            

Summary

The Summary output mode uses three styles. The first two styles change the summary, whereas the third is for highlighting inputs that have errors.

The complete CSS styles for the Summary output mode are below:

.validity-summary-container { display:none; }
.validity-summary-output ul { }
.validity-erroneous { border:solid 2px #f56600 !important; }
            

When adapting these styles, the only property that should not be changed is the display:none; which is applied to elements with the CSS class validity-summary-container. This will keep the summary hidden by default so that it will not be shown when the page loads.

The UL element inside the container will house the errors. If you would like to modify the bullet-style or anything else to do with the list this second style will be where to do it.

This is the summary:
  • Here's a validation message.
  • Here's another validation message.

Customizing Messages

You can modify the default error messages that are built into Validity. If you dislike the wording of any of these default messages you may override them easily. Executing the following code will overrite all of the messages.

$.extend($.validity.messages, {
    require:"#{field} is required.",

    // Format validators:
    match:"#{field} is in an invalid format.",
    integer:"#{field} must be a positive, whole number.",
    date:"#{field} must be formatted as a date.",
    email:"#{field} must be formatted as an email.",
    usd:"#{field} must be formatted as a US Dollar amount.",
    url:"#{field} must be formatted as a URL.",
    number:"#{field} must be formatted as a number.",
    zip:"#{field} must be formatted as a zipcode ##### or #####-####.",
    phone:"#{field} must be formatted as a phone number ###-###-####.",
    guid:"#{field} must be formatted as a guid like {3F2504E0-4F89-11D3-9A0C-0305E82C3301}.",
    time24:"#{field} must be formatted as a 24 hour time: 23:00.",
    time12:"#{field} must be formatted as a 12 hour time: 12:00 AM/PM",

    // Value range messages:
    lessThan:"#{field} must be less than #{max}.",
    lessThanOrEqualTo:"#{field} must be less than or equal to #{max}.",
    greaterThan:"#{field} must be greater than #{min}.",
    greaterThanOrEqualTo:"#{field} must be greater than or equal to #{min}.",
    range:"#{field} must be between #{min} and #{max}.",

    // Value length messages:
    tooLong:"#{field} cannot be longer than #{max} characters.",
    tooShort:"#{field} cannot be shorter than #{min} characters.}",

    // Aggregate validator messages:
    equal:"Values don't match.",
    distinct:"A value was repeated.",
    sum:"Values don't add to #{sum}.",
    sumMax:"The sum of the values must be less than #{max}.",
    sumMin:"The sum of the values must be greater than #{min}.",

    nonHtml:"#{field} cannot contain Html characters.",

    generic:"Invalid."
});
            

With the above code snippet, you may edit any of the strings and Validity will subsequently use that for the default message. As an alternative syntax you may simply edit the strings in the following way:

$.validity.messages.match = "The format of #{field} is totally wrong.";
            

Please note that the #{field} token is never used in aggregate validator messages because they do not deal with any particular field. (See Tokenized Messages.)


Customizing/Extending Match Validator Support

You can add more format checkers to the Validity match validator with the following syntax.

// Adds match validator support to format-check against list of email addresses 
// separated by semicolons.
// Lovingly borrowed from http://regexlib.com/REDetails.aspx?regexp_id=1007

// Add the pattern:
$.validity.patterns.emailList = /^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$/;

// Add the message under the same name:
$.validity.messages.emailList = "#{field} must be formatted as a series of email-addresses separated by semicolons.";
            

As you can see, we add the pattern under the name emailList and also add a message under the same name. Now that that's been executed, we can pass that name into the match validator. For example:

// You can simply use the name of your new format and pass it in as a string:
$("#ListOfEmailAddresses")
    .require()
    .match("emailList");
            

Note that, when adding a format to the match validator, adding the message is optional, but recommended.

Using the same syntax, you are also able to override the Regular Expressions used by the built-in formats.


Language Packages/Internationalization

Because of the many ways that Validity can be customized, writing an Internationalization package is relatively simple. As an example the following code will install a Russian-language package which will change the validation messages into Russian and change some of the match-validator expressions:

$.extend($.validity.messages, {
    require:"#{field} обязательное поле.",
    match:"#{field} неправильный формат.",
    integer:"#{field} должно быть положительным числом.",
    date:"#{field} должно быть отформатирован как дата. (число.месяц.Год, 04.05.2006)",
    email:"#{field} должно быть отформатированы как адреса электронной почты.",
    usd:"#{field} должно быть отформатированы как деньги США.",
    url:"#{field} должно быть отформатированы как URL.",
    number:"#{field} должно быть отформатирован в виде числа.",
    zip:"#{field} должно быть отформатированы как почтовый индекс. (###)",
    phone:"#{field} должно быть отформатированы как телефонный номер.",
    guid:"#{field} должно быть отформатированы как GUID (как {3F2504E0-4F89-11D3-9A0C-0305E82C3301}).",
    time24:"#{field} должно быть отформатированы 24-часовой.",
    time12:"#{field} должно быть отформатированы 12-часовой. (12:00 AM/PM)",

    // Value range messages:
    lessThan:"#{field} должно быть меньше #{max}.",
    lessThanOrEqualTo:"#{field} должно быть меньше или равным #{max}.",
    greaterThan:"#{field} должно быть больше #{min}.",
    greaterThanOrEqualTo:"#{field} должно быть больше или равно #{min}.",
    range:"#{field} должно быть между #{min} и #{max}.",

    // Value length messages:
    tooLong:"#{field} может быть не более #{max} букв.",
    tooShort:"#{field} может быть не меньше #{min} букв.}",

    // Aggregate validator messages:
    equal:"Значения не равны.",
    distinct:"Было повторено значения.",
    sum:"Показатели не добавить до #{sum}.",
    sumMax:"Сумма значений должно быть меньше #{max}.",
    sumMin:"Сумма значений должно быть больше #{min}.",

    nonHtml:"#{field} не может содержать символы HTML.",

    generic:"Неверно."
});

$.validity.setup({ defaultFieldName:"поле" });

$.extend($.validity.patterns, {
    // Based off of http://en.wikipedia.org/wiki/Calendar_date
    date:/^([012]\d|30|31)\.([01]\d)\.\d{1,4}$/, 
    
    // Russian postal codes, based off of http://en.wikipedia.org/wiki/List_of_postal_codes_in_Russia
    zip: /^\d{3}$/,
    
    // Russian phone number pattern from http://regexlib.com/REDetails.aspx?regexp_id=1463
    phone: /((8|\+7)-?)?\(?\d{3,5}\)?-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}((-?\d{1})?-?\d{1})?/
});
            

Writing a Custom Output Mode

A major goal of Validity is to allow complete control over how validation messages appear so that they can look like they belong in your site. If adapting the CSS of any of the existing output modes isn't sufficient to make it look right you can write your own output mode from the ground up.

This may sound difficult, but thanks to Validity's philosophy of Separation of Interests it's really rather trivial. It involves two steps: first you install your custom output mode, then you enable it.

Here's a template for creating your own custom output mode. The code is actually very sparce, but may look complex on account of all the comments:

(function(){

    // The output mode will be named whatever you assign it to.
    // In this example, since we're assigning it to 'myOutputMode'
    // it will be called 'myOutputMode'.
    $.validity.outputs.myOutputMode = {
    
        // The start function will be called when validation starts.
        // This allows you to prepare the page for validation, for instance
        // you might remove any validation messages that are already on the page.
        start:function(){ 
        
        },
        
        // The end function is called when validation has concluded.
        // This allows you to flush any buffers or do anything you need to
        // after all of the validators have been called.
        // results will be the results object.
        // results.valid is a boolean representing whether the form is valid.
        // results.errors is an integer of how many errors there are.
        end:function(results) { 
        
        },
        
        // The raise function is called to raise an error for a specific input.
        // The first argument is a jQuery object of the input to raise the error message for.
        // The second argument is the string of the error message.
        raise:function($obj, msg){
        
        },
        
        // The raiseAggregate function is similar to the raise function, except that
        // the $obj argument will be a jQuery object of several inputs, 
        // all of which are invalid aggregately.
        raiseAggregate:function($obj, msg){ 
        
        },
    }
})();

// Now enable the output mode we just installed.
$.validity.setup({ outputMode:'myOutputMode' });
            

As an example, here is an output mode that will raise a JavaScript alert box, and then animate the border of the bad input:

// First install the new output mode:
(function(){
    
    // We'll decide to install our custom output mode under the name 'custom':
    $.validity.outputs.custom = {
        
        // In this case, the start function will just reset the inputs:
        start:function(){ 
        
            $("input:text")
                .css({border:'1px solid green'})
                .removeClass('fail');
                
        },
        
        end:function(results) { 
        
            // If not valid and scrollTo is enabled, scroll the page to the first error.
            if (!results.valid && $.validity.settings.scrollTo) {
                location.hash = $(".fail:eq(0)").attr('id')
            }
            
        },
        
        // Our raise function will display the error and animate the text-box:
        raise:function($obj, msg){
            
            // Make the JavaScript alert box with the message:
            alert(msg);
            
            // Animate the border of the text box:
            $obj
                .animate({ borderWidth: "10px" }, 1000)
                .css({borderColor:'red'})
                .addClass('fail');
                
        },
        
        // Our aggregate raise will just raise the error on the last input:
        raiseAggregate:function($obj, msg){ 
        
            this.raise($($obj.get($obj.length - 1)), msg); 
            
        }
    }
})();

// Now enable the output mode we just installed.
$.validity.setup({ outputMode:'custom' });

// Our custom output mode is installed and will be used whenever Validity is run.
            

Below is an example of this output mode in action. Try submitting it without entering anything in the text-box.

<html>
  <head>
    <title>Custom Output</title>
    <script type="text/javascript" src="../../jquery.js"></script>
    <script type="text/javascript" src="../../jquery.validity.js"></script>
    <script type="text/javascript">
        (function(){
            $.validity.outputs.custom = {
                start:function(){ 
                    $("input:text")
                        .css({border:'1px solid green'})
                        .removeClass('fail');
                },
                
                end:function(results) {
                    // If not valid and scrollTo is enabled, scroll the page to the first error.
                    if (!results.valid && $.validity.settings.scrollTo) {
                        location.hash = $(".fail:eq(0)").attr('id')
                    }
                },
                
                raise:function($obj, msg){
                    alert(msg);
                    $obj
                        .animate({ borderWidth: "10px" }, 1000)
                        .css({borderColor:'red'})
                        .addClass('fail');
                },
                
                // Just raise the error on the last input.
                raiseAggregate:function($obj, msg){ 
                    this.raise($($obj.get($obj.length - 1)), msg); 
                }
            }
            
            $.validity.setup({ outputMode:'custom' });
        })();
          
        // Instruct validity to validate the page by requiring 
        // the input matched by a jQuery selector.
        $(function() { $("form").validity("#text"); });
    </script>
  </head>
  <body>
    <form action="customoutput.htm" method="post">
      This field is required:
      <input type="text" id="text" name="text" style="border:solid 1px green" />
      <input type="submit" />
    </form>
  </body>
</html>

                

Using the template above, you can easily make your own output mode and package it nicely in its own, reuseable, easily shared JavaScript file.


Miscellaneous


The Setup Function

Validity supplies a setup function to let you modify global Validity settings. The syntax for this function, and all of the settings you have access to are below:

$.validity.setup({
    // You may change the output mode with this property.
    outputMode: "label",

    // The this property is set to true, validity will scroll the browser viewport
    // so that the first error is visible when validation fails.
    scrollTo: false,

    // If this setting is true, modal errors will disappear when they are clicked on.
    modalErrorsClickable: true,

    // If a field name cannot be otherwise inferred, this will be used.
    defaultFieldName: "This field"
});
            

You may edit any or all of these settings at once.




2017. 6. 23. 13:56

jquery validate ajax form submit 2가지 방법

1. validate 의 submitHandler 를 사용하는 방법

$('#form-id').validate({
    rules : { ... },
    submitHandler: function(f) {
        $.ajax(
            url: f.action,
            type: f.method,
            data: $(f).serialize(),
            success: function(response) {
                alert(response);
            }
        );
    }
});

2. jquery 의 ajaxForm을 사용하는 방법

$('#form-id').ajaxForm({
    beforeSubmit: function() {
        $('#form-id').validate({......});
        return $('#form-id').valid();
    },
    success: function(response) {
        alert(response);
    }
});



2012. 1. 4. 10:10

JQuery UI position 유틸리티

JQuery UI dialog, menu 등의 팝업을 특정 위치에 오픈되도록 하는 방법

1. 마우스의 위치에 따라 결정되게 하는 방법
 - 마우스 좌표를 저장한 후 position 값에 x, y 를 준다.

var x = null;
var y = null;
$(document).ready(function() {
    $(document).mousemove(function (e) {
        x = e.clientX; y = e.clientY;
    });     
   
$('#id').dialog({position: [x, y]});
});



2. 특정 개체의 위치에 의해 결정되게 하는 방법

$(
document).ready(function() {
    $('#id').dialog({
        position: {
            my : 'left top',
            at : 'right top',
            of : '#id2'
        }
    });
});
 

my : dialog 의 위치 (#id)
at : 위치할 개체의 위치 (#id2)
of : 위치할 개체

위의 설정은 dialog 의 왼쪽 위 모서리를 #id2 개체의 오른쪽 위 모서리에 위치하겠다는 설정임.
단 JQuery UI 의 Position 유틸리티가 설치되어야 한다.

http://jqueryui.com/demos/position/  

Position 유틸리티의 좌표계는 아래 이미지를 참고



2011. 12. 15. 17:15

fancybox api

You can pass options as key/value object to fancybox() function or modify them at the bottom of FancyBox JS file. These are options for 1.3+, for versions 1.2+ look there.

KeyDefault valueDescription
padding 10 Space between FancyBox wrapper and content
margin 20 Space between viewport and FancyBox wrapper
opacity false When true, transparency of content is changed for elastic transitions
modal false When true, 'overlayShow' is set to 'true' and 'hideOnOverlayClick', 'hideOnContentClick', 'enableEscapeButton', 'showCloseButton' are set to 'false'
cyclic false When true, galleries will be cyclic, allowing you to keep pressing next/back.
scrolling 'auto' Set the overflow CSS property to create or hide scrollbars. Can be set to 'auto', 'yes', or 'no'
width 560 Width for content types 'iframe' and 'swf'. Also set for inline content if 'autoDimensions' is set to 'false'
height 340 Height for content types 'iframe' and 'swf'. Also set for inline content if 'autoDimensions' is set to 'false'
autoScale true If true, FancyBox is scaled to fit in viewport
autoDimensions true For inline and ajax views, resizes the view to the element recieves. Make sure it has dimensions otherwise this will give unexpected results
centerOnScroll false When true, FancyBox is centered while scrolling page
ajax { } Ajax options 
Note: 'error' and 'success' will be overwritten by FancyBox
swf {wmode: 'transparent'} Params to put on the swf object
hideOnOverlayClick true Toggle if clicking the overlay should close FancyBox
hideOnContentClick false Toggle if clicking the content should close FancyBox
overlayShow true Toggle overlay
overlayOpacity 0.3 Opacity of the overlay (from 0 to 1; default - 0.3)
overlayColor '#666' Color of the overlay
titleShow true Toggle title
titlePosition 'outside' The position of title. Can be set to 'outside', 'inside' or 'over'
titleFormat null Callback to customize title area. You can set any html - custom image counter or even custom navigation
transitionIn, transitionOut 'fade' The transition type. Can be set to 'elastic', 'fade' or 'none'
speedIn, speedOut 300 Speed of the fade and elastic transitions, in milliseconds
changeSpeed 300 Speed of resizing when changing gallery items, in milliseconds
changeFade 'fast' Speed of the content fading while changing gallery items
easingIn, easingOut 'swing' Easing used for elastic animations
showCloseButton true Toggle close button
showNavArrows true Toggle navigation arrows
enableEscapeButton true Toggle if pressing Esc button closes FancyBox
onStart null Will be called right before attempting to load the content
onCancel null Will be called after loading is canceled
onComplete null Will be called once the content is displayed
onCleanup null Will be called just before closing
onClosed null Will be called once FancyBox is closed

KeyDescription
type Forces content type. Can be set to 'image', 'ajax', 'iframe', 'swf' or 'inline'
href Forces content source
title Forces title
content Forces content (can be any html data)
orig Sets object whos position and dimensions will be used by 'elastic' transition
index Custom start index of manually created gallery (since 1.3.1)

FancyBox provides some function to work with it

MethodDescription
$.fancybox.showActivity Shows loading animation
$.fancybox.hideActivity Hides loading animation
$.fancybox.next Displays the next gallery item
$.fancybox.prev Displays the previous gallery item
$.fancybox.pos Displays item by index from gallery
$.fancybox.cancel Cancels loading content
$.fancybox.close Hides FancyBox 
Within an iframe use - parent.$.fancybox.close();
$.fancybox.resize Auto-resizes FancyBox height to match height of content
$.fancybox.center Centers FancyBox in viewport

7. Custom title formating - lightbox style

JavaScript

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();"><img src="/data/closelabel.gif" /></a></span>' + (title && title.length ? '<b>' + title + '</b>' : '' ) + 'Image ' + (currentIndex + 1) + ' of ' + currentArray.length + '</div>';
}

$(".tip7").fancybox({
	'showCloseButton'	: false,
	'titlePosition' 		: 'inside',
	'titleFormat'		: formatTitle
});

CSS

#tip7-title { text-align: left; }

#tip7-title b { display: block; margin-right: 80px; }

#tip7-title span { float: right; }

Example 
tip7 tip7

6. Start FancyBox on page load

If you have attached FancyBox than you can trigger click method

jQuery(document).ready(function() {
    $("#your_selector").trigger('click');
});

Alternative method is to use manual call

jQuery(document).ready(function() {
	$.fancybox(
		'<h2>Hi!</h2><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis mi eu elit tempor facilisis id et neque</p>',
		{
        		'autoDimensions'	: false,
			'width'         		: 350,
			'height'        		: 'auto',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none'
		}
	);
});

5. Display login form Try now

Sample HTML form:

<div style="display:none">
	<form id="login_form" method="post" action="">
	    	<p id="login_error">Please, enter data</p>
		<p>
			<label for="login_name">Login: </label>
			<input type="text" id="login_name" name="login_name" size="30" />
		</p>
		<p>
			<label for="login_pass">Password: </label>
			<input type="password" id="login_pass" name="login_pass" size="30" />
		</p>
		<p>
			<input type="submit" value="Login" />
		</p>
		<p>
		    <em>Leave empty so see resizing</em>
		</p>
	</form>
</div>

Attach FancyBox:

$("#tip5").fancybox({
	'scrolling'		: 'no',
	'titleShow'		: false,
	'onClosed'		: function() {
	    $("#login_error").hide();
	}
});

Simple validation; submit data using Ajax and display response

$("#login_form").bind("submit", function() {

	if ($("#login_name").val().length < 1 || $("#login_pass").val().length < 1) {
	    $("#login_error").show();
	    $.fancybox.resize();
	    return false;
	}

	$.fancybox.showActivity();

	$.ajax({
		type		: "POST",
		cache	: false,
		url		: "/data/login.php",
		data		: $(this).serializeArray(),
		success: function(data) {
			$.fancybox(data);
		}
	});

	return false;
});

4. Show youtube clips. Try now

This script also enables full screen mode if video's href has the parameter &fs=1

$("#tip4").click(function() {
	$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'		: 680,
			'height'		: 495,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			   	 'wmode'		: 'transparent',
				'allowfullscreen'	: 'true'
			}
		});

	return false;
});

3. Show/hide title on hover. Try now

$("#tip3").fancybox({
	'titlePosition'	:	'over',
	'onComplete'	:	function() {
		$("#fancybox-wrap").hover(function() {
			$("#fancybox-title").show();
		}, function() {
			$("#fancybox-title").hide();
		});
	}
});

2. Select all anchor tags that contain image tags

$("a:has(img)").fancybox();

Alternative method - apply Fancybox to only those <a> tags that have href attributes that end with .jpg, .png or .gif:

$("a[href$='.jpg'],a[href$='.png'],a[href$='.gif']").fancybox();

1. Create gallery from jQuery object collection

$("a.fancybox").attr('rel', 'gallery').fancybox();

fancybox 가 버젼2로 업데이트 되면서 혹시나 없어질지도 몰라 따로 포스팅해놓음


2011. 12. 9. 11:15

jquery 관련 (메모)

1. jquery ui dialog 기본값 설정 방법
$.extend($.ui.dialog.prototype.options, {
show: "blind",
        hide: "explode",
        width: 300,
        height: 230,
        resizable: false,
        position: [x, y],
        zIndex: 10000,
        buttons: {
        '닫기' : function() {
                $(this).dialog('close');
            }
        }
}); 

2. jquery ui dialog 모든 창 닫기 
$(".ui-dialog-content").dialog("close"); 

3. jquery ui datepicker 창을 아래쪽으로만 뜨게하기
$.extend($.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});

4. jquery ui autocomplete 항목조절
$('#CompanyName').autocomplete(...)..data('autocomplete')._renderItem = function(ul, item) {
    //여기에 조건을 주고 모양을 설정해주면 됨
    if(item.value === '') {
        return $('<li class="ui-menu-item disabled" style="color:#aaa;text-decoration: line-through">' + item.label + ' (disabled)</li>').appendTo(ul);
    } else {
        return $("<li></li>")
                   .data("item.autocomplete", item)
                   .append("<a class='ui-corner-all'>" + item.label + "</a>")
                   .appendTo(ul);
    }
}


2010. 11. 3. 14:44

Jquery SELECT 태그 관련 내용

// 뒤쪽에 옵션 추가

$("#myselect").append("<option value='1'>Apples</option>");
$("#myselect").append("<option value='2'>After Apples</option>");

// 앞쪽에 옵션 삽입
$("#myselect").prepend("<option value='0'>Before Apples</option>");

// 옵션변경
$("#myselect").html("<option value='1'>Some oranges</option><option value='2'>More Oranges</option><option value='3'>Even more oranges</option>");

// 인덱스 위치에 따라 옵션 변경
$("#myselect option:eq(1)").replaceWith("<option value='2'>Some apples</option>");
$("#myselect option:eq(2)").replaceWith("<option value='3'>Some bananas</option>");

// 2번째 옵션 셀렉트
$("#myselect option:eq(2)").attr("selected", "selected");

// 해당 텍스트를 가진 옵션 셀렉트
$("#myselect").val("Some oranges").attr("selected", "selected");

// 해당값을 가진 옵션 셀렉트
$("#myselect").val("2");

// 선택 옵션 제거
$("#myselect option:eq(0)").remove();

// 첫번째 옵션 제거
$("#myselect option:first").remove();

// 마지막 옵션 제거
$("#myselect option:last").remove();

// 셀렉트된 옵션 텍스트 리턴
alert($("#myselect option:selected").text());

// 셀렉트된 옵션 값리턴
alert($("#myselect option:selected").val());

// 셀렉트된 인덱스 리턴
alert($("#myselect option").index($("#myselect option:selected")));

// Alternative way to get the selected item
alert($("#myselect option:selected").prevAll().size());

// Insert an item in after a particular position
$("#myselect option:eq(0)").after("<option value='4'>Some pears</option>");

// Insert an item in before a particular position
$("#myselect option:eq(3)").before("<option value='5'>Some apricots</option>");

// Getting values when item is selected
$("#myselect").change(function() {
    alert($(this).val());
    alert($(this).children("option:selected").text());
});