Nick Ginanto
Nick Ginanto

Reputation: 32140

Cannot select checkbox with jquery - Unexpected identifier

I am trying to select this checkbox and test if it is checked

<input class="controls" id="user_regret_avatar" label="Delete My Picture" name="user[regret_avatar]" type="checkbox" value="1">

with this

if $("#user_regret_avatar").attr('checked') {
    alert("yay");
}
else{
alert("aww");
};

but I am getting

Uncaught SyntaxError: Unexpected identifier 

is my selector bad?

also note - I've seen http://api.jquery.com/prop/, I've checked all the checked tests.. still same issue

Now with fiddle - Can't get the test going

Upvotes: 0

Views: 389

Answers (2)

Florian Mertens
Florian Mertens

Reputation: 2448

The following code worked for me:

<html>
<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
function displayItems()
{
    //$('#table_numbers input:checkbox:checked')
    if ($("#user_regret_avatar").attr('checked')) {
        alert("yay");
    }
    else {
        alert("aww");
    }
}
    </script>
    <title>SEARCH</title>
</head>
<body>
    <form method="post" action="1004mcout.php">
        <input class="controls" id="user_regret_avatar" label="Delete My Picture" name="user[regret_avatar]" type="checkbox" value="1">
        <input type="button" onclick="displayItems();" />
    </form>

</body> 
</html>

I think you forgot to surround the if statement with brackets:

if ($("#user_regret_avatar").attr('checked')) {...

Upvotes: 1

Amyth
Amyth

Reputation: 32949

You need to change the if condition as follows :

if ($("#user_regret_avatar").attr('checked')) {
    alert("yay");
} else {
alert("aww");
};

Note the () after if:

Here is a working JSFiddle

Upvotes: 1

Related Questions