Citizen
Citizen

Reputation: 12957

Checkbox onChange submit problem if checked

The purpose is to have a checkbox, that if clicked, will send via post where I will update the db. The user can check back and forth to set or unset active status.

This works perfectly:

<form name='form".$value['id']."' action='./filter_edit.php' method='post'><input type='checkbox' name='checkbox[".$value['id']."]' value='".$newActive."' onclick='document.form".$value['id'].".submit();' /></form>

However, using the code above, the box never appears checked.

With the below code, once the field is set to active where the box will be checked, clicking to uncheck the box does submit but sends no post variables.

<form name='form".$value['id']."' action='./filter_edit.php' method='post'><input type='checkbox' name='checkbox[".$value['id']."]' value='".$newActive."'";
        if($value['active'] == 1)
            echo " checked='checked'";
        echo" onclick='document.form".$value['id'].".submit();' /></form>

Upvotes: 0

Views: 3109

Answers (4)

jb8578
jb8578

Reputation: 1

Change: value='".$newActive."'

To just: ".$newActive."

I'm assuming $newActive is either = "checked" or "" to determine whether the checkbox is checked or not.

Upvotes: 0

Ryan Florence
Ryan Florence

Reputation: 13483

An unchecked checkbox sends nothing in the post parameters.

You have to do that logic on the server: check for the post variable, if it's not there then you know it was unchecked.

Upvotes: 2

Narcissus
Narcissus

Reputation: 3194

I'm guessing the problem is that the Javascript is processed before the item itself is 'clicked' (if that makes sense): that is to say, the form is submitted before the checkbox is actually checked.

If you were to mark the checkbox as checked from within the Javascript before running the submit, I would guess that that would work.

Upvotes: 1

Citizen
Citizen

Reputation: 12957

Found a solution to my problem, kind of. Basically instead of using the checkbox to pass the variable, I use the checkbox only for display (of being checked or not) and then use a hidden field to pass the value.

Upvotes: 1

Related Questions