Top jquery Questions

List of Tags
1610
Philip Morton

In jQuery, suppose you have an element of some kind that you're hiding and showing, using .hide(), .show() or .toggle(). How do you test to see if that element is currently hidden or visible on the screen?

Answered By: Tsvetomir Tsonev ( 2263)

As, the question refers to a single element, this code might be more suitable:

$(element).is(":visible") // Checks for display:[none|block], ignores visible:[true|false]

Same as twernt's suggestion, but applied to a single element.

Is there a plugin-less way of retrieving query string values via jQuery (or without)?

If so, how, and if not what plugin do you recommend?

Answered By: Artem Barger ( 1598)

You don't need jQuery for that purpose. You can use the pure JavaScript:

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}
1177
venkatachalam

How can I redirect the user from one page to another using jQuery?

Answered By: Ryan McGeary ( 2737)

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

It is better than using window.location.href =, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

For example:

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
943
Jeffrey Schrab

What is the most efficient way to clone a JavaScript object? I've seen:

obj = eval(uneval(o));

but that's not cross platform (FF only). I've done (in Mootools 1.2) things like this:

obj = JSON.decode(JSON.encode(o));

but question the efficiency. I've also seen recursive copying function, etc. I'm pretty surprised that out-of-the-box JavaScript doesn't have a method for doing this.

Answered By: John Resig ( 1594)

I want to note that the .clone() method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.

I have a layout similar to this

<div id="..."><img src="..."></div>

I would like to use a jQuery selector to select the child img inside of the div on click

To get the div, I've got this selector:

$(this)

How do I get the img with a selector?

Answered By: Simon ( 1270)

The jQuery constructor accepts a 2nd parameter which can be used to override the context of the selection.

jQuery("img", this);

Which is the same as

jQuery(this).find("img");

If the imgs are direct descendants of the clicked element, you can also use:

jQuery(this).children("img");
798
Prasad

I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery.

For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox.

But the following code returns false by default:

if($('#isAgeSelected').attr('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

How do I successfully query the checked property?

Answered By: karim79 ( 1015)

Try this:

if ($('#isAgeSelected').is(':checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
} 

You can shorten this using ternary, some might say it's a bit less readable, but that's how I would do it:

$('#isAgeSelected').is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();

EDIT (14 months later): There's a much prettier way to do this, using toggle:

$('#isAgeSelected').click(function () {
    $("#txtAge").toggle(this.checked);
});

<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>​

Fiddle Demo

753
tpower

I want to do something like this

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

I wish to set the value.

Is such a thing built into jQuery?

Answered By: Xian ( 1260)

It certainly is in

jQuery 1.6+

Use the new .prop() function:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

jQuery 1.5 and below

The .prop() function is not available, so you need to use .attr().

To check the checkbox (by setting the value of the checked attribute) do

$('.myCheckbox').attr('checked','checked');

and for un-checking (by removing the attribute entirely) do

$('.myCheckbox').removeAttr('checked');

Any version of jQuery

If you're working with just one element, it will always be fastest to use DOMElement.checked = true. The benefit to using the .prop() and .attr() functions is that they will operate on all matched elements.

// Assuming an event handler on a checkbox
if (this.checked)
663
Mark Struzinski

I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

/Date(1224043200000)/

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here's the solution I came up with using a combination of the answers here:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch", 
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

Answered By: Roy Tinker ( 688)

Eval is not necessary. This will work fine:

var date = new Date(parseInt(jsonDate.substr(6)));

The substr function takes out the "\/Date(" part, and the parseInt function gets the integer and ignores the ")\/" at the end. The resulting number is passed into the Date constructor.

635
Darryl Hein

What is the best method in jQuery to add an additional row to a table as the last row?

Update

Is this acceptable:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?

Answered By: Luke Bennett ( 611)

The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a tbody for example:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
</table>

You would end up with the following:

<table id="myTable">
  <tbody>
    <tr>...</tr>
    <tr>...</tr>
  </tbody>
  <tr>...</tr>
</table>

I would therefore recommend this approach instead:

$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');

You can include anything within the after() method as long as it's valid HTML, including multiple rows as per the example above.

Update: Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a tbody in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no tbody unless you have specified one yourself.

DaRKoN_ suggests appending to the tbody rather than adding content after the last tr. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple tbody elements and the row would get added to each of them.

Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.

I think the safest solution is probably to ensure your table always includes at least one tbody in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple tbody elements):

$('#myTable > tbody:last').append('<tr>...</tr><tr>...</tr>');
579
cletus

There are a few JavaScript frameworks/toolsets out there, such as:

It certainly seems that jQuery is ascendant in terms of mindshare at the moment. For example, Microsoft (ASP.NET MVC) and Nokia will use it. I also found this performance comparison of Dojo, jQuery, MooTools and Prototype (Edit: Updated Comparison), which looks highly favourable to Dojo and jQuery.

Now my previous experience with JavaScript has been the old school HTML + JavaScript most of us have done and RIA frameworks like Google Web Toolkit ("GWT") and Ext-GWT, which were a fairly low-stress entry into the Ajax world for someone from a Java background, such as myself.

But, after all this, I find myself leaning towards the more PHP + Ajax type solution, which just seems that much more lightweight.

So I've been looking into jQuery and I really like its use of commands, the use of fluent interfaces and method chaining, its cross-browser CSS selector superset, the fact that it's lightweight and extensible, the brevity of the syntax, unobtrusive JavaScript and the plug-in framework. Now obviously many of these aren't unique to jQuery but on the basis that some things are greater than their sum of parts, it just seems that it all fits together and works well.

So jQuery seems to have a lot going for it and it looks to the frontrunner for what I choose to concentrate on. Is there anything else I should be aware of or any particular reasons not to choose it or to choose something else?

EDIT: I just wanted to add this trend comparison of JavaScript frameworks.

Answered By: Pim Jager ( 529)

jQuery

  • Fast
  • Well documented
  • Easy to use
  • Chaining
  • Unlike Prototype it doesn't extend an object if you didn't specifically ask for it (try looping an array in Prototype)
  • easy-to-use Ajax (I love the $.ajaxSetup() function)
  • Nice event handlers
  • CSS selectors
  • filtering your selection
  • did I mention chaining?
  • Small (only 30 KB)
  • Nice little built-in effects.
  • Plugins