korben
korben

Reputation: 537

jquery if checkbox is checked, alert with result isn't working

I can't figure out what's wrong with this code. It is supposed to check if a checkbox is checked, and alert "checked" if it is and "not checked" if it's not. However it keeps returning the "checked" result every time.

$(document).ready(function () {
        $('#midmenusubmit').click(function () {
            if ($('input:c2:checked').val() != undefined) {
                alert("checked");
                //checked
            }
            else {
                alert("not checked");
                //not checked
            }

        });
    });


<input type="checkbox" id="c2" name="c2" ></input>


<img src="image.png" id="midmenusubmit" />

Upvotes: 1

Views: 6341

Answers (2)

Chris Meek
Chris Meek

Reputation: 5839

Better to use

$('input:c2:checked').length > 0

or

$('input:c2').is(':checked') // returns true or false

The .val() is looking for a value on the input element and never finds it hence it always being undefined

Upvotes: 2

BoltClock
BoltClock

Reputation: 723538

Here's a more succinct way to check the state of your checkbox:

if ($('input#c2').is(':checked')) {

Upvotes: 5

Related Questions