Mike
Mike

Reputation: 265

Check current and previous checkboxes

I am quite new to jquery and javascript to be honest and I am having trouble with checkboxes.

This works as #checkAll is a checkbox used for checking all the other checkboxes with class "check":

function test() {
if($("#checkAll").prop('checked')) {
    $(".check").prop('checked', true);
} else {
    $(".check").prop('checked', false);
}
}

However, I want it to work when I select any checkbox. So I tried putting the function to all checkboxes as a click event, just using onclick="test()".

I think the problem is that I am trying to use $(this) but I must be using it wrongly, what I have is:

function test() {
if($(this).prop("checked")) {
    $(".check").prop("checked", true);
} else {
    $(".check").prop("checked", false);
}
}

"$(this)" also has the class "check", so maybe it's to do with that.

Ultimately I want to check one box and it check all previous checkboxes, not ones that come afterwards. I think if I get my head around why this isn't working then I should be able to figure that out. I'm not lazy, just learning!!

I have searched for an answer but cannot find one. I'm hoping someone can help.

Thanks in advance!

Upvotes: 1

Views: 1137

Answers (3)

Scimonster
Scimonster

Reputation: 33409

When you do onclick="test()", you call test() in the global context, so this is going to be set to window, not your DOM element. You can solve this in a couple ways.

You could D4V1D's solution, passing a parameter.

You could also use test.call(this), to manually force the context to be the DOM element.

You could also attach the event handlers via jQuery instead of as attributes:

$(".check").click(test);

jQuery will automatically call the callback with the correct context.

BTW, i recommend you look at prevAll for what you want to do next.

Upvotes: 2

Adrian Lynch
Adrian Lynch

Reputation: 8494

Given this HTML:

<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>
<input type='checkbox'>

Here's some jQuery to check all previous checkboxes:

$("input[type='checkbox']").click(function(e) {
    $(e.target).prevAll().prop("checked", true);
});

Upvotes: 0

D4V1D
D4V1D

Reputation: 5849

Pass this as a parameter of your function as such:

onclick="test(this);"

And use it in your function like so:

function test(that) {
    if($(that).prop('checked')) {}
}

Upvotes: 2

Related Questions