XanderNGCC
XanderNGCC

Reputation: 75

jQuery Select Individual Checkbox in Group

I'm trying to simply select one individual checkbox in a group of boxes and can't figure it out.

Here is the code that creates my checkbox group dynamically. I need to be able to loop through and select individual boxes that were checked previously by the user:

<?php
    //Display all "cheese" options in a checkbox group
    foreach($_SESSION['ingr_cheese'] as $key => $value)
    {
        echo "<div class=\"cheesebox\" style=\"float:left; width:175px; margin-bottom:7px;\">";
        echo "<input type=\"checkbox\" name=\"cheese1\" class=\"cheeseCheck\" value=\"".$key."\">&nbsp;<label for=\"cheese1\">".$value['cheese']."</label></br>";
        echo "</div>";
    }
?>

Once I figure out how to check just one I can figure out the loop. Here is the jQuery code I'm trying to select just the checkbox with index value "1":

$("#cheese1:checkbox:eq('1')").attr("selected", true);

Upvotes: 0

Views: 552

Answers (1)

Jacob VanScoy
Jacob VanScoy

Reputation: 1168

You want to use the checked attribute instead of the selected attribute and select the checkboxes this way instead of using the :checked selector. For jQuery 1.6 and above do:

$('div.cheesebox input[type=checkbox]').eq(1).prop('checked', true);

For jQuery < 1.6 do:

$('div.cheesebox input[type=checkbox]').eq(1).attr('checked', 'checked');

Upvotes: 2

Related Questions