Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

Submit in jquery

<html>
<head>
  <style>

  p { margin:0; color:blue; }
  div,p { margin-left:10px; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Type 'correct' to validate.</p>
  <form action="javascript:alert('success!');">
    <div>
      <input type="text" />

      <input type="submit" />
    </div>
  </form>
  <span></span>
<script>

    $("form").submit(function() {
      if ($("input:first").val() == "correct") {//first input tag,
  //if ($("input:second").val() == "correct") {second input tag,
        $("span").text("Validated...").show();//for all span
        return true;
      }
      $("span").text("Not valid!").show().fadeOut(1000);
      return false;
    });
</script>

</body>
</html>



<html>
<head>
  <style>

  p { margin:0; color:blue; }
  div,p { margin-left:10px; }
  span { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Type 'correct' to validate.</p>
 <form id="target" action="destination.html">
  <input type="text" value="Hello there" />
  <input type="submit" value="Go" />
</form>
<div id="other">
  Trigger the handler
</div>
  <span></span>
<script>

   $('#target').submit(function() {
  alert('Handler for .submit() called.');
  return false;
});
$('#other').click(function() {
  $('#target').submit();
});
</script>

</body>
</html>

Ready() event in jquery

.ready( handler ) Returns: jQuery

Description: Specify a function to execute when the DOM is fully loaded.
  • version added: 1.0.ready( handler )

    handlerA function to execute after the DOM is ready.
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.
The .ready() method is generally incompatible with the <body onload=""> attribute. If load must be used, either do not use .ready() or use jQuery's .load() method to attach load event handlers to the window or to more specific items, like images.
All three of the following syntaxes are equivalent:
  • $(document).ready(handler)
  • $().ready(handler) (this is not recommended)
  • $(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
The .ready() method can only be called on a jQuery object matching the current document, so the selector can be omitted.
The .ready() method is typically used with an anonymous function:
$(document).ready(function() {
  // Handler for .ready() called.
});
Which is equivalent to calling:
$(function() {
 // Handler for .ready() called.
});
If .ready() is called after the DOM has been initialized, the new handler passed in will be executed immediately.

Aliasing the jQuery Namespace

When using another JavaScript library, we may wish to call $.noConflict() to avoid namespace difficulties. When this function is called, the $ shortcut is no longer available, forcing us to write jQuery each time we would normally write $. However, the handler passed to the .ready() method can take an argument, which is passed the global jQuery object. This means we can rename the object within the context of our .ready() handler without affecting other code:
jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Example:

Display a message when the DOM is loaded.

<!DOCTYPE html>
<html>
<head>
  <style>p { color:red; }</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function () {
  $("p").text("The DOM is now loaded and can be manipulated.");
});
  </script>
</head>
<body>
  <p>Not loaded yet.</p>
</body>
</html>

Load in jQuery

  • .load( handler(eventObject) )

    handler(eventObject)A function to execute when the event is triggered.
  • version added: 1.4.3.load( [eventData], handler(eventObject) )

    eventDataA map of data that will be passed to the event handler.
    handler(eventObject)A function to execute each time the event is triggered.
This method is a shortcut for .bind('load', handler).
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
For example, consider a page with a simple image:
<img src="book.png" alt="Book" id="book" />
The event handler can be bound to the image:
$('#book').load(function() {
  // Handler for .load() called.
});
As soon as the image has been loaded, the handler is called.
In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the .ready() method.
The Ajax module also has a method named .load(). Which one is fired depends on the set of arguments passed.
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree
  • Can cease to fire for images that already live in the browser's cache
Note: The .live() and .delegate() methods cannot be used to detect the load event of an iframe. The load event does not correctly bubble up the parent document and the event.target isn't set by Firefox, IE9 or Chrome, which is required to do event delegation.

Examples:

Example: Run a function when the page is fully loaded including graphics.

$(window).load(function () {
  // run code
});

Example: Add the class bigImg to all images with height greater then 100 upon each image load.

$('img.userIcon').load(function(){
  if($(this).height() > 100) {
    $(this).addClass('bigImg');
  }
});

Value in JQuery

http://api.jquery.com/val/

.val()

Contents:

.val() Returns: String, Number, Array

Description: Get the current value of the first element in the set of matched elements.
  • version added: 1.0.val()

The .val() method is primarily used to get the values of form elements such as input, select and textarea. In the case of <select multiple="multiple"> elements, the .val() method returns an array containing each selected option.
For selects and checkboxes, you can also use the :selected and :checked selectors to get at values, for example:
$('select.foo option:selected').val();    // get the value from a dropdown select
$('select.foo').val();                    // get the value from a dropdown select even easier
$('input:checkbox:checked').val();        // get the value from a checked checkbox
$('input:radio[name=bar]:checked').val(); // get the value from a set of radio buttons
Note: At present, using .val() on textarea elements strips carriage return characters from the browser-reported value. When this value is sent to the server via XHR however, carriage returns are preserved (or added by browsers which do not include them in the raw value). A workaround for this issue can be achieved using a valHook as follows:
$.valHooks.textarea = {
    get: function( elem ) {
        return elem.value.replace( /\r?\n/g, "\r\n" );
    }
};

Examples:

Example: Get the single value from a single select and an array of values from a multiple select and display their values.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:red; margin:4px; }
  b { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p></p>

  <select id="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select>
<script>
    function displayVals() {
      var singleValues = $("#single").val();// return value for the control which id id single
      var multipleValues = $("#multiple").val() || [];// return value for the control which id id multiple as its mor so array will return
      $("p").html("<b>Single:</b> " + 
                  singleValues +
                  " <b>Multiple:</b> " + 
                  multipleValues.join(", "));
    }

    $("select").change(displayVals);// For All Select change event
//$("#multiple").change(displayVals); // For ID
    displayVals(); //Automatically called
</script>
</body>
</html>

Demo:

Example: Find the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" value="some text"/>
  <p></p>
<script>
    $("input").keyup(function () {
      var value = $(this).val();
      $("p").text(value);
    }).keyup();
</script>
</body>
</html>
 
Same as 
 
<html>
<head>
  <style>

  p { color:blue; margin:8px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <input type="text" id="text" value="some text"/>
  <p></p>
<script>
    
 function f11() {
      var value = $("#text").val();
      $("p").text(value);
    }
$("input").keyup(f11);
f11()
</script>

</body>
</html> 

Demo:

.val( value ) Returns: jQuery

Description: Set the value of each element in the set of matched elements.
  • version added: 1.0.val( value )

    valueA string of text or an array of strings corresponding to the value of each matched element to set as selected/checked.
  • version added: 1.4.val( function(index, value) )

    function(index, value)A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
This method is typically used to set the values of form fields.
Passing an array of element values allows matching <input type="checkbox">, <input type="radio"> and <option>s inside of n <select multiple="multiple"> to be selected. In the case of <input type="radio">s that are part of a radio group and <select multiple="multiple"> the other elements will be deselected.
The .val() method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:
$('input:text.items').val(function( index, value ) {
  return value + ' ' + this.className;
});
This example appends the string " items" to the text inputs' values.

Examples:

Example: Set the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <style>
  button { margin:4px; cursor:pointer; }
  input { margin:4px; color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div>
    <button>Feed</button>
    <button>the</button>
    <button>Input</button>
  </div>
  <input type="text" value="click a button" />
<script>
    $("button").click(function () {
      var text = $(this).text();
      $("input").val(text);
    });
</script>
</body>
</html>

Demo:

Example: Use the function argument to modify the value of an input box.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
  <p>Type something and then click or tab out of the input.</p>
  <input type="text" value="type something" />
<script>
  $('input').bind('blur', function() {
    $(this).val(function( i, val ) {
      return val.toUpperCase();
    });
  });
  </script>
</body>
</html>

Demo:

Example: Set a single select, a multiple select, checkboxes and a radio button .

<!DOCTYPE html>
<html>
<head>
  <style>
  body { color:blue; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <select id="single">
    <option>Single</option>
    <option>Single2</option>
  </select>

  <select id="multiple" multiple="multiple">
    <option selected="selected">Multiple</option>
    <option>Multiple2</option>
    <option selected="selected">Multiple3</option>
  </select><br/>
  <input type="checkbox" name="checkboxname" value="check1"/> check1
  <input type="checkbox" name="checkboxname" value="check2"/> check2
  <input type="radio"  name="r" value="radio1"/> radio1
  <input type="radio"  name="r" value="radio2"/> radio2<script>
    
    $("#single").val("Single2");//From begining Single2 wiil be selected
    $("#multiple").val(["Multiple2", "Multiple3"]); //From begining Multiple2,Multiple3 wiil be selected
    $("input").val(["check1","check2", "radio1" ]);//From begining check1,check2 and radio1 wiil be selected
</script>
</body>
</html>

Demo:

JQuery assign value to a hdn field

ALL<P>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("p").click(function(){       //$("p") is for all <p> ; $("#p") is id of a control
   $("#hdn").val("Pradeepta");//$("#control id").val(value);
alert($("#hdn").val())              //.click is for click event
  });
});
</script>
</head>
<body>
<input type="hidden" name="hdn"  id="hdn"/>
<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>
</html>

ID OF < P >
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#p1").click(function(){
   $("#hdn").val("Pradeepta");
alert($("#hdn").val())
  });
});
</script>
</head>
<body>
<input type="hidden" name="hdn"  id="hdn"/>
<p>If you click on me, I will disappear.</p>
<p id="p1">Click me away!</p>
<p>Click me too!</p>
</body>
</html>

Jquery for beginners

Link to jQuery’s Source Code Remotely

This is an optional technique that many developers are using today. Instead of hosting the jQuery source code on your own server, you can link to it remotely. This ensures the fastest possible download time of the source code, since many users visiting your site might have the file already cached in their browser. Here is how your <script> tag should look:
  1. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js?ver=1.4.0"></script>  

Running Code Unobtrusively When the DOM is Ready

The first thing you need to be up and running with jQuery is what’s called the “document ready” handler. Pretty much everything you code in jQuery will be contained inside one of these. This accomplishes two things: First, it ensures that the code does not run until the DOM is ready. This confirms that any elements being accessed are actually in existence, so the script won’t return any errors. Second, this ensures that your code is unobtrusive. That is, it’s separated from content (HTML) and presentation (CSS).
Here is what it looks like:
  1. $(document).ready(function() {  
  2.     // all jQuery code goes here  
  3. });  
Although you will normally include your jQuery code inside the above handler, for brevity the rest of the code examples in this tutorial will not include the “ready” handler.

Selecting Elements in jQuery

The jQuery library allows you to select elements in your HTML by wrapping them in $("") (you could also use single quotes), which is the jQuery wrapper. Here are some examples of “wrapped sets” in jQuery:
  1. $("div"); // selects all HTML div elements  
  2. $("#myElement"); // selects one HTML element with ID "myElement"  
  3. $(".myClass"); // selects HTML elements with class "myClass"  
  4. $("p#myElement"); // selects paragraph elements with ID "myElement"  
  5. $("ul li a.navigation"); // selects anchors with class "navigation" that are nested in list items  
jQuery supports the use of all CSS selectors, even those in CSS3. Here are some examples of alternate selectors:
  1. $("p > a"); // selects anchors that are direct children of paragraphs  
  2. $("input[type=text]"); // selects inputs that have specified type  
  3. $("a:first"); // selects the first anchor on the page  
  4. $("p:odd"); // selects all odd numbered paragraphs  
  5. $("li:first-child"); // every list item that's first child in a list  
jQuery also allows the use of its own custom selectors. Here are some examples:
  1. $(":animated"); // selects elements currently being animated  
  2. $(":button"); // selects any button elements (inputs or buttons)  
  3. $(":radio"); // selects radio buttons  
  4. $(":checkbox"); // selects checkboxes  
  5. $(":checked"); // selects selected checkboxes or radio buttons  
  6. $(":header"); // selects header elements (h1, h2, h3, etc.)  
View a list of jQuery’s selectors and custom selectors

Manipulating and Accessing CSS Class Names

jQuery allows you to easily add, remove, and toggle CSS classes, which comes in handy for a variety of practical uses. Here are the different syntaxes for accomplishing this:
  1. $("div").addClass("content"); // adds class "content" to all <div> elements  
  2. $("div").removeClass("content"); // removes class "content" from all <div> elements  
  3. $("div").toggleClass("content"); // toggles the class "content" on all <div> elements (adds it if it doesn't exist, and removes it if it does)  
You can also check to see if a selected element has a particular CSS class, and then run some code if it does. You would check this using an if statement. Here is an example:
  1. if ($("#myElement").hasClass("content")) {  
  2.     // do something here  
  3. }  
You could also check a set of elements (instead of just one), and the result would return “true” if any one of the elements contained the class.

Manipulating CSS Styles with jQuery

CSS styles can be added to elements easily using jQuery, and it’s done in a cross-browser fashion. Here are some examples to demonstrate this:
  1. $("p").css("width", "400px"); // adds a width to all paragraphs  
  2. $("#myElement").css("color", "blue") // makes text color blue on element #myElement  
  3. $("ul").css("border", "solid 1px #ccc") // adds a border to all lists  
View more CSS-related commands for jQuery

Adding, Removing, and Appending Elements and Content

There are a number of ways to manipulate groups of elements with jQuery, including manipulating the content of those elements (whether text, inline elements, etc).
Get the HTML of any element (similar to innerHTML in JavaScript):
  1. var myElementHTML = $("#myElement").html(); // variable contains all HTML (including text) inside #myElement  
If you don’t want to access the HTML, but only want the text of an element:
  1. var myElementHTML = $("#myElement").text(); // variable contains all text (excluding HTML) inside #myElement  
Using similar syntax to the above two examples, you can change the HTML or text content of a specified element:
  1. $("#myElement").html("<p>This is the new content.</p>"); // content inside #myElement will be replaced with that specified  
  2. $("#myElement").text("This is the new content."); // text content will be replaced with that specified  
To append content to an element:
  1. $("#myElement").append("<p>This is the new content.</p>"); // keeps content intact, and adds the new content to the end  
  2. $("p").append("<p>This is the new content.</p>"); // add the same content to all paragraphs  
jQuery also offers use of the commands appendTo(), prepend(), prependTo(), before(), insertBefore(), after(), insertAfter(), which work similarly to append but with their own unique characteristics that go beyond the scope of this simple tutorial.
View more info on some of the above commands

Dealing with Events in jQuery

Specific event handlers can be established using the following code:
  1. $("a").click(function() {  
  2.     // do something here  
  3.     // when any anchor is clicked  
  4. });  
The code inside function() will only run when an anchor is clicked. Some other common events you might use in jQuery include:
blur, focus, hover, keydown, load, mousemove, resize, scroll, submit, select.
View a more comprehensive list of jQuery events

Showing and Hiding Elements with jQuery

The syntax for showing, hiding an element (or toggling show/hide) is:
  1. $("#myElement").hide("slow", function() {  
  2.     // do something once the element is hidden  
  3. }  
  4.   
  5. $("#myElement").show("fast", function() {  
  6.     // do something once the element is shown  
  7. }  
  8.   
  9. $("#myElement").toggle(1000, function() {  
  10.     // do something once the element is shown/hidden  
  11. }  
Remember that the “toggle” command will change whatever state the element currently has, and the parameters are both optional. The first parameter indicates the speed of the showing/hiding. If no speed is set, it will occur instantly, with no animation. A number for “speed” represents the speed in milliseconds. The second parameter is an optional function that will run when the command is finished executing.
You can also specifically choose to fade an element in or out, which is always done by animation:
  1. $("#myElement").fadeOut("slow", function() {  
  2.     // do something when fade out finished  
  3. }  
  4.   
  5. $("#myElement").fadeIn("fast", function() {  
  6.     // do something when fade in finished  
  7. }  
To fade an element only partially, either in or out:
  1. $("#myElement").fadeTo(2000, 0.4, function() {  
  2.     // do something when fade is finished  
  3. }  
The second parameter (0.4) represents “opacity”, and is similar to the way opacity is set in CSS. Whatever the opacity is to start with, it will animate (fadeTo) until it reaches the setting specified, at the speed set (2000 milliseconds). The optional function (called a “callback function”) will run when the opacity change is complete. This is the way virtually all callback functions in jQuery work.

jQuery Animations and Effects

You can slide elements, animate elements, and even stop animations in mid-sequence. To slide elements up or down:
  1. $("#myElement").slideDown("fast", function() {  
  2.     // do something when slide down is finished  
  3. }  
  4.   
  5. $("#myElement").slideUp("slow", function() {  
  6.     // do something when slide up is finished  
  7. }  
  8.   
  9. $("#myElement").slideToggle(1000, function() {  
  10.     // do something when slide up/down is finished  
  11. }  
To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles, but instead of setting them instantly (as CSS or raw JavaScript would do), it does so gradually, animating the effect at the chosen speed:
  1. $("#myElement").animate(  
  2.     {  
  3.         opacity: .3,  
  4.         width: "500px",  
  5.         height: "700px"  
  6.     }, 2000, function() {  
  7.         // optional callback after animation completes  
  8.     }  
  9. );  
Animation with jQuery is very powerful, and it does have its quirks (for example, to animate colors, you need a special plugin). It’s worth taking the time to learn to use the animate command in depth, but it is quite easy to use even for beginners.
More info on the animate() command
More info on other effects-related jQuery commands