views:

181

answers:

7

Hi,

Can you help turn the following Javascript to jQuery equivalent?

// Let's use a lowercase function name to keep with JavaScript conventions
function selectAll(involker) {
    // Since ASP.NET checkboxes are really HTML input elements
    //  let's get all the inputs
    var inputElements = document.getElementsByTagName('input');

    for (var i = 0; i < inputElements.length; i++) {
        var myElement = inputElements[i];

        // Filter through the input types looking for checkboxes
        if (myElement.type === "checkbox") {

            // Use the involker (our calling element) as the reference 
            //  for our checkbox status
            myElement.checked = involker.checked;
        }
    }
}

It's from here http://wiki.asp.net/page.aspx/281/check-uncheck-checkboxes-in-gridview-using-javascript/

+5  A: 
function selectAll(involker) {
    $('input:checkbox').attr('checked', $(involker).attr('checked'));
}
David Hedlund
surely it'd be better to pass in the 'checked' attribute as a var instead of doing a test on it multiple times? (although for all I know this may be streamlined by the interpreter)
Ed Woodcock
In the code above, it is only tested once. $(. . .).attr loops over the results of the query.
Kyle Butt
I'm a jQuery newbie. This helps me a lot. Thank you.
narazana
@Kyle: yes, the attr('checked' . .) bit is done once per checkbox, but, as far as I'm aware, so is accessing the $(involker).attr('checked'), which would be better outside that loop.
Ed Woodcock
Ed Woodcock is right. Even better, use the couldn't-be-simpler DOM property rather than `attr()` to get the checkedness of `involker`: `var check = involker.checked;`. Even better still, use that same easy-peasy DOM `checked` property to set the checkedness of the target checkbox, as per my answer.
Tim Down
+2  A: 

Just by:

function selectAll(involker) {
  $('input:checkbox').attr('checked', involker.checked);
}
CMS
+1  A: 
$('input:checkbox').attr('checked', involker.checked);

Also it's "invoker" not "involker".

Pointy
it's involker in the asp.net referred to =)
David Hedlund
well yes, my eyes aren't that bad, and you'll notice I spelled it that way in the code.
Pointy
i just meant you shouldn't be telling narazana this, but adam kahtava at asp.net if anyone =)
David Hedlund
I would not assume his object is named invoker and not involker...
Mark Schultheiss
@Pointy @David I need to learn how to spell! My typo. :)
Adam Kahtava
+2  A: 

Let's make it jquery style!

$('type here the selector for invoker').click(function(){
    $('input:checkbox').attr('checked', $(this).attr('checked'));
});
naugtur
A: 

Assuming the same HTML as the example, you'll want to remove the event attributes (i.e. OnClick="selectAll(this)") and use this unobtrusive Javascript:

$(document).ready( function() {
    $('#cbSelectAll').click( function() {
      $('input:checkbox').attr( 'checked', $(this).attr('checked') );
    });
});
DisgruntledGoat
while i'll agree that you want to remove the event attributes, naugtur's example is how to properly set the value in that case.
David Hedlund
Why will the OP necessarily want to do that? Maybe he/she will want the function to be called even if the checkbox is clicked before the document has finished loading.
Tim Down
@David: Yes you're right, my original solution didn't toggle the checkbox. @Tim: I added the standard jQuery `document.ready` code, which solves that problem.
DisgruntledGoat
I think what Tim meant was that the declarative assignment, through `onClick="..."` will give that checkbox the click listener immediately, whereas the jQuery way, with `$(document).ready` as he probably inferred, will not bind the event until the entire DOM is loaded (although often before the *page* has finished loading)
David Hedlund
Indeed I did, yes.
Tim Down
True, but it's pretty useless until all the checkboxes have loaded anyway. As soon as the user can see all the checkboxes, this should work.
DisgruntledGoat
+1  A: 

My answer will be similar to others except to point out that using attr() is a really bad way to get or set the checkedness of a checkbox. It's longer, harder to read, slower and more error-prone, since it goes through all sorts of unnecessary jQuery function calls and falsely implies that it has something to do with attributes.

function selectAll(invoker) {
    var check = invoker.checked;
    $('input:checkbox').each( function() { this.checked = check; } );
}
Tim Down
i'll give you that accessing the DOM node's checked state in plain JS will be the faster way of achieving this, but it certainly isn't the jQueryest. seems to me the OP just wanted to learn some jQuery, and i'd argue you don't learn that by plain JS examples. If it's just the speed you're after, this will still be slower than the function provided in the question. and I wouldn't agree that manually iterating the set with `each` is more readable than using jQuery's set-based functions. The ability to set properties over an entire set of elements might be the single strongest feature of jQuery
David Hedlund
I partly agree. First, if jQueryness means not learning *any* simple DOM techniques, even where they're simpler than the jQuery equivalent, then I can't recommend it. I'm suggesting that slavishly doing everything in a jQuery style because, hell, it's there and I'm damn well going to use it, is not a good way to go. Use it for what it's good at, namely selecting and iterating over collections of nodes in the DOM. Once you're writing the bit that manipulates a DOM node, chances are there's an easy DOM method or property that does what you need and I think it's better to use it. [continued]
Tim Down
Regarding my answer, it's a shame I was forced into using `each` to iterate over the selected nodes because it does harm the readability, and I entirely concede that my answer will be slower than the OP's function: it's inevitable since it's using jQuery. However, I strongly disagree with using jQuery for trivial DOM operations, particularly the woolly misconceptions that the `attr()` method seems to breed in people's minds, and gave an example of how the original task could be done (in my view) sensibly using jQuery.
Tim Down
A: 

Just to give a variety of options and add information for others.

To address replacement of your function: Set all the checkboxes to match the current checked status of involker:

function selectAll(involker) 
{
    $("input:checkbox").attr("checked",involker.checked);
};

OTHER:

Set all the checkboxes currently checked to match the current checked status of involker:

function selectAll(involker) 
{
    $("input:checkbox:checked").attr("checked",involker.checked);
};

Set all the checkboxes NOT checked to match the current checked status of involker:

function selectAll(involker) 
{
    $("input:checkbox:not(:checked").attr("checked",involker.checked);
};

And to toss in another I have found useful with a "master checkbox/button clicker": toggle all of the checkboxes from current state

Set all the checkboxes to opposite of their current setting:(assumption of object with id='toggleCheckboxes' attribute)

$('#toggleCheckboxes').click(function()
{
    $("input:checkbox").each(function() {
        this.checked = !this.checked;
    });
});

Set all the checkboxes to match the current setting of master checkbox:(assumption of input checkbox object with id='masterCheckbox' attribute)

$('#masterCheckbox:checkbox').change(function()
{
    var master = this.checked;
    $(".childCheckbox input:checkbox").each(function() {
        this.checked = master;
    });
});
Mark Schultheiss