ドキュメント

Frequently Asked Questions

From jQuery JavaScript Library

Jump to: navigation, search

These are some questions frequently asked by others while using jQuery to do cool things. If you have a new question, please post it to the Mailing List.

Contents

How do I ... ?

How do I select an item using class or id?

  • This code selects an element with an id of "myDivId". Since id's are unique this expression always selects 1 element, or none if the id does not exist.
  $('#myDivId')
  • This code selects an element with a class of "myCssClass". Since any number of elements can have the same class, this expression will select any number of elements.
  $('.myCssClass')

A selected element can be assigned to a javascript variable like this

  var myDivElement = $('#myDivId');

Usually selected elements are acted on by other JQuery functions:

  var myValue = $('#myDivId').val();    // get the value of an element

  $('#myDivId').val("hello world");     // set the value of an element

How do I test whether an element has a particular class?

(Sometimes also: Does jQuery have a hasClass method?)

  • You can use the is() method along with an appropriate selector
 if ( $('#myDiv').is('.pretty') )
   $('#myDiv').show();

Note that this method allows you to test for other things as well. For example, you can test whether an element is hidden (by using the custom :hidden selector):

 if ( $('#myDiv').is(':hidden') )
   $('#myDiv').show();
  • Note also that hasClass has been added as of version 1.2 to handle the most common use of is():
$("div").click(function(){
  if ( $(this).hasClass("protected") )
    $(this)
      .animate({ left: -10 })
      .animate({ left: 10 })
      .animate({ left: -10 })
      .animate({ left: 10 })
      .animate({ left: 0 });
});

How do I test whether an element exists?

  • You can use the length property of the jQuery collection returned by your selector:
if ( $('#myDiv').length )
  $('#myDiv').show();

Note: It isn't always necessary to test whether an element exists. The following code would show the item if it exists, and do nothing (no errors) if it did not:

$('#myDiv').show();

How do I determine the state of a toggled element?

You can check the state using the :visible or :hidden selectors.

 var isVisible = $('#myDiv').is(':visible');
 var isHidden = $('#myDiv').is(':hidden');

If you're simply acting on an element based on its visibility, just include ":visible" or ":hidden" in the selector expression. For example:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');

How do I select an element by an ID that has characters used in CSS notation?

Because jQuery uses CSS syntax for selecting elements, some characters are interpreted as CSS notation. For example, ID attributes, after an initial letter (a-z or A-Z), may also use periods and colons, in addition to letters, numbers, hyphens, and underscores (see W3C Basic HTML Data Types). The colon (":") and period (".") are problematic within the context of a jQuery selector because they indicate a pseudo-class and class, respectively.

In order to have jQuery treat these characters literally rather than as CSS notation, they must be "escaped" by placing two backslashes in front of them.

 // Does not work
 $("#some:id")
 
 // Works!
 $("#some\\:id")
 // Does not work
 $("#some.id")
 
 // Works!
 $("#some\\.id")

The following function takes care of escaping these characters and places a "#" at the beginning of the ID string:

 function jq(myid) { 
   return '#' + myid.replace(/(:|\.)/g,'\\$1');
 }


The function can be used like so:

 $( jq('some.id') )

How do I disable/enable an element?

You can disable/enable an element by setting the 'disabled' attribute to 'disabled' (to disable it) or "" (to enable it). The result of which looks something like this:

 // Disable #x
 $("#x").attr("disabled","disabled");
 // Enable #x
 $("#x").removeAttr("disabled");

You can try an example of enabling/disabling with the following demo:

and here's the source code to the demo:

 <select id="x" style="width:200px;">
   <option>one</option>
   <option>two</option>
 </select>
 <input type="button" value="Disable" onclick="$('#x').attr('disabled','disabled')"/>
 <input type="button" value="Enable" onclick="$('#x').removeAttr('disabled')"/>

How do I check/uncheck an input?

You can check/uncheck an element by setting the 'checked' attribute to 'checked' (to check it) or "" (to uncheck it). The result of which looks something like this:

 // Check #x
 $("#c").attr("checked", "checked");
 // Uncheck #x
 $("#c").removeAttr("checked");

You can try an example of checking/unchecking with the following demo:

and here's the source code to the demo:

 <label><input type="checkbox" id="c"/> I'll be checked/unchecked.</label>
 <input type="button" value="Check" onclick='$("#c").attr("checked","checked")'/>
 <input type="button" value="Uncheck" onclick='$("#c").removeAttr("checked")'/>

How do I get the text value of a selected option?

Select elements typically have two values that you want to access. First there's the value, which is easy:

 $("select#myselect").val();
 // => 1

Next is getting the textual value of a select. For example, if you had the following select box:

 <select id="myselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">haseeb</option>
 </select>

And you wanted to get the string "Mr" if the first option was selected (instead of just "1"). You would do that in the following way:

 $("#myselect option:selected").text();
 // => "Mr"

You can see this in action in the following demo:

and here's the full source code to the demo:

 <select id="myselect">
   <option value="1">Mr</option>
   <option value="2">Mrs</option>
   <option value="3">Ms</option>
   <option value="4">Dr</option>
   <option value="5">Prof</option>
 </select>
 <input type="button" value="Get Value" onclick="alert($('#myselect').val())"/>
 <input type="button" value="Get Text Value" onclick="alert($('#myselect option:selected').text())"/>

How do I replace text from the 3rd element of a list of 10 items?

Either the :eq() selector or the .eq() method will allow you to select the proper item. However, to replace the text, you must get the value before you set it:

  // This doesn't work
  $(this).find('li a').eq(2).text().replace('foo','bar');

  // This works 
  var $thirdLink = $(this).find('li a').eq(2);
  var linkText = $thirdLink.text().replace('foo','bar');
  $thirdLink.text(linkText); 
  

The first way only returns the string to you -- the second way is required to actually replace it. Remember, .text() gets; .text("foo") sets. However, the trick here is that replace() is a JavaScript string method, not a jquery method. Thus, you have to return the string from the inner part, inside the outer part, in order to set its value.

How do I compress my code?

Generally the best way to do it is to use the YUI compressor.

An alternative is to use Douglas Crockford's JSMin. This doesn't compress JavaScript code as small, but generally how you write your code matters less. jQuery also provides a pre-minified version of jQuery for your convenience.

Packing javascript using Dean Edwards' Packer (specifically using the base64 encode) is not recommended, as the client-side decoding has significant overhead that outweighs the file-size benefits.

If compressing your JavaScript breaks it, try running the code through JSLint. This will detect minor errors that can cause packed JavaScript to fail where the unpacked version works fine.

How do I submit a bug report?

You can submit a bug report through the jQuery bug tracker.

Any information you can provide will help, such as:

  • A detailed bug report,
  • An online demo page, showing the problem,
  • A specific piece of code that is affected, or
  • A pointer to the area in jQuery where the bug occurs.

The more information a bug report has, the more likely it will be to get fixed. If a long period of time has gone by without an update to your bug, please bring it up for discussion on the jQuery Dev List.

How do I get and use the server response from an AJAX request?

The 'A' in AJAX stands for asynchronous. When invoking functions that have asynchronous behavior you must provide a callback function to capture the desired result. This is especially important with AJAX in the browser because when a remote request is made, it is indeterminate when (or even if) the response will be received.

The following snippet shows an example of making an AJAX call and alerting the response (or error):

 $.ajax({
     url: 'myPage.php',
     success: function(response) {
        alert(response);
     },
     error: function(xhr) {
        alert('Error!  Status = ' + xhr.status);
     }
 });

But how can the response be used in context of a function? Consider this flawed example where we try to update some status information on the page:

 function updateStatus() {
     var status;
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             status = response;
         }
     });
     // update status element?  this will not work as expected
     $('#status').html(status);
 }

The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined. The next snippet shows how we can rewrite this function to behave as desired:

 function updateStatus() {
     $.ajax({
         url: 'getStatus.php',
         success: function(response) {
             // update status element
             $('#status').html(response);
         }
     });
 }

But how can I return the server response from an AJAX call? Here again we show a flawed attempt. In this example we attempt to alert the http status code for the url of 'getStatus.php':

 //...
 alert(getUrlStatus('getStatus.php'));
 //...
 function getUrlStatus(url) {
     $.ajax({
         url: url,
         complete: function(xhr) {
             return xhr.status;
         }
     });
 }

The code above will not work, of course. Instead, it must be rewritten to use a callback:

 //...
 getUrlStatus('getStatus.php', function(status) {
     alert(status);
 });
 // ...
 function getUrlStatus(url, callback) {
     $.ajax({
         url: url,
         complete: function(xhr) {
             callback(xhr.status);
         }
     });
 }

Why do ... ?

Why do my events stop working after an AJAX request?

Frequently, when you've added a click (or other event) handler to all links using $('a').click(fn) you'll find that the events no longer work after you've loaded new content into a page using an AJAX request.

When you call $('a') it returns all the links on the page at the time and .click(fn) adds your handler to each individual element. When new links are added, they are unaffected. See the AJAX and Events Tutorial for longer discussion.

You have two ways of handling this:

Re-binding

This method implicates calling the method .bind() on the new added elements, as they are loaded/added. For example:

 $('a').click(fn);
 $('#mydiv').load('my.html',function(){
   $('a').click(fn);
 });

Beware not to bind on the same element/s over and over, or the function will be executed many times on each click (or any other event).

To learn more about event re-binding read this article on the Learning jQuery blog

Use the Live Query Plugin

Take a look at the Live Query plugin, by Brandon Aaron. It allows you to write something like this:

 $('a').livequery('click',fn);
 $('#mydiv').load('my.html');

The Live Query plugin automatically re-binds events to their target, even after you've loaded content in from a remote page.

Use Event Delegation

Event Delegation is a technique upheld by Event Bubbling. To handle events that bubble this way, you bind to a common container, and passively listen for events from there.

 $('#mydiv').click(function(e){
    if( $(e.target).is('a') )
       fn.call(e.target,e);
 });
 $('#mydiv').load('my.html');

jQuery Methods

As of jQuery 1.3, you can use the live and die methods for event delegation with a subset of event types.

Plugins for event delegation

Intercept, by Ariel Flesler, accepts any valid selector, and also a collection of selector/function.

 $('#mydiv').intercept('click', 'a', fn);
 $('#mydiv').load('my.html');

Listen, also by Ariel Flesler, can scale much better than its counterparts, it is able to handle large amounts of selectors with nearly no additional overhead. The downside is, that it only supports 4 kind of selectors.

 $('#mydiv').listen('click', 'a', fn);
 $('#mydiv').load('my.html');

If you want to read further: check out this great article by Karl Swedberg.

Why doesn't an event work on a new element I've created?

As explained in the previous question about AJAX, events are bound only to elements that exist when you issue the jQuery call. When you create a new element, you must rebind the event to it.

You can avoid this extra step by using the Live Query plugin, as explained in the previous question about Ajax.

As of jQuery 1.3, you can use the live method for a subset of event types. Use the Live Query Plugin using jQuery Live pluginas explained by logo design:

  1.
      
  2.
     $('li')
  3.
       .livequery(function() {
  4.
         $(this)
  5.
           .hover(function() {
  6.
             $(this).addClass('hover');
  7.
           }, function() {
  8.
             $(this).removeClass('hover');
  9.
           });
 10.
       }, function() {
 11.
         $(this)
 12.
           .unbind('mouseover')
 13.
           .unbind('mouseout');
 14.
       });

Why do animations set the display style to block?

To start with, you need to remember that only block-style elements can have a custom width or height. When you do an animation on an element that animates the height or width (such as show, hide, slideUp, or slideDown) then the display style property will be set to 'block' for the duration of the animation. The display property will be reverted to its original value after the animation completes.

There are two common workarounds:

If you want to have the element stay inline, but you just want it to animate in or out, you can use the fadeIn or fadeOut animations - which only affect the opacity of an element (and thus, don't need to have its display changed).

 // Instead of this:
 $("span").show("slow");
 
 // do this:
 $("span").fadeIn("slow");

The other option is to use a block-level element, but to add a float such that it appears to stay inline with the rest of the content around it. The result might looks something like this:

 // A floated block element
 <div style="float:left;">...</div>
 
 // Your code:
 $("div").show("slow");

Cookbook

Recipe: Simple menu with hover to show sub-menu items

Recipe: Hide All divs Except One

Recipe: Multi-select Listbox without the Ctrl key

See the following for possible solutions: