Jquery – Allow only one checkbox selected when certain button clicked

checkboxjquery

I have the following code:

$("input.edit_user").click(function() {
    var theCheckboxes = $("input[type='checkbox']"); 
    if (theCheckboxes.filter(":checked").length > 1)
        $(this).removeAttr("checked");
        alert( "Please selected one user at a time for editing." );
});
.
.
.
<tr>
    <td><input type="checkbox" name="user_id[]" value="1"></td>
    <td><input type="checkbox" name="user_id[]" value="2"></td>
    <td><input type="checkbox" name="user_id[]" value="3"></td>
</tr>
.
.
.
<input type="submit" name="submit" value="Edit Selected User" class="edit_user">

I'm using checkboxes, because there are other options that allow for more than one item to be selected.

However, When a user selects a checkbox for editing, I need to alert them they are only allowed to select one checkbox at a time.

I think I have the right idea with my code, but I'm going about it the wrong way, since it's not working and just continues to process the page normally.

Suggestions?


UPDATE on selected solution and why

For the viable solutions below, once I added:

$(document).ready(function() { 

in my working example, they started working. I selected the answer I did, because after the above line was added, all I needed was the

return false;

line (and correct brackets on the inner if statement) in order to stop the page from executing what remains.

Thank you all for your help solving this!

Best Answer

I think you have to return false:

$("input.edit_user").click(function() {
    var theCheckboxes = $("input[type='checkbox']"); 
    if (theCheckboxes.filter(":checked").length > 1) {
        $(this).removeAttr("checked");
        alert( "Please selected one user at a time for editing." );

        return false;
    }
});