ANKIT
ANKIT

Reputation: 561

jQuery: Check if checkbox is checked

i have an html page where i have multiple "checkboxes" each of them are call a function onclick.

Something like this

onclick="manage(val1, val2)

And in my function when i am getting the check status of checkbox, giving false every time.

function manage(val1, val2) {
    **if ($(this).is(":checked")) {** //returns false everytime
        //do something
        //
    }
    else {
        //do something
    }
}

please tell me where i am doing mistake...

Thanks in advance

Upvotes: 0

Views: 3595

Answers (3)

Sinetheta
Sinetheta

Reputation: 9449

You'll need to set the context of your onclick, or pass it 'this' as a parameter:

<input type="checkbox" onclick="manage(this, 'val1', 'val2');"></input>
<script>
function manage(that, val1, val2) {
   if ($(that).is(":checked")) {
       alert('checked')
    }
    else {
       alert('unchecked')
    }
}
</script>

jsFiddle

Of course your best bet is to NOT use in-line javascript, go with something like TerryR wrote.

Upvotes: 2

Adam Rackis
Adam Rackis

Reputation: 83376

When manage(val1, val2) is called, this will be the global object (or undefined if you're in strict mode)

But you can set the this value manually with call. Try this:

onclick="manage.call(this, val1, val2);"

Now this will be whatever you just clicked on.

Just to clarify a bit more, inside the onclick="____" this is the thinig you clicked on. But once you call functions from there, this becomes the global object in the functions. So:

onclick="foo(this);"

function foo(val) {
    alert(this);
    alert(val);
}

Alerts [object DomWindow] (the global object) then [object HtmlInputElement] (the thing I clicked on)

Without getting into too much detail, this is a result of how "function invocation" works in JavaScript.

Upvotes: 5

Terry
Terry

Reputation: 14219

$('input[type="checkbox"]').click(function(){  // append click to any checkbox
    if ($(this).is(':checked')) {
        // do something
    }
});

Upvotes: 5

Related Questions