checkbox value problem in $_POST

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
devarishi
Forum Contributor
Posts: 101
Joined: Fri Feb 05, 2010 7:15 pm

checkbox value problem in $_POST

Post by devarishi »

Consider this HTML and JavaScript which I Have in my PHP Script:

Code: Select all

IVR Updated <input type="checkbox" name="IVR" value="Yes" onClick='chkIVR(this.form)';>

Code: Select all

    function chkIVR(theForm) {
 
        if (theForm.IVR.checked) {
            theForm.IVR.value = "Yes";
        }
 
        else {
            theForm.IVR.value = "No";
        }
 
    alert(theForm.IVR.value);
 
    }

When we check it, I get "Yes" in

echo $_POST['IVR'];

But when it is unchecked, no value is POSTed. Why?
User avatar
Sofw_Arch_Dev
Forum Commoner
Posts: 60
Joined: Tue Mar 16, 2010 4:06 pm
Location: San Francisco, California, US

Re: checkbox value problem in $_POST

Post by Sofw_Arch_Dev »

This is how HTML forms work. Checkbox values are only sent if the checkbox is CHECKED.
User avatar
cap2cap10
Forum Contributor
Posts: 158
Joined: Mon Apr 14, 2008 11:06 pm

Re: checkbox value problem in $_POST

Post by cap2cap10 »

If the information is going to a database, then simply set the default value in db to "no". But, yes, if the checkbox is not selected, that information associated with the checkbox is not sent.

Batoe
devarishi
Forum Contributor
Posts: 101
Joined: Fri Feb 05, 2010 7:15 pm

Re: checkbox value problem in $_POST

Post by devarishi »

I devised the following method:

First set the default value "Yes" (checked) onLoad() even of the page that is in <body> and then OnChange() event was attached to the checkbox which would assign corresponding values to a hidden element. This way, whether checkbox is checked or not, I still have a valud value! :mrgreen: :drunk:

Code: Select all

function chkIVR(theForm) {
 
        if (theForm.IVR.checked) {
            theForm.v_IVR.value = "Yes";
        }
 
        else {
            theForm.v_IVR.value = "No";
 
        }
 
        alert(theForm.v_IVR.value);
 
    }
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: checkbox value problem in $_POST

Post by Benjamin »

What happens when your users have disabled javascript?

Why not this:

Code: Select all

$cbValue = (isset($_POST['checkbox']) && $_POST['checkbox'] == 'checked') ? 'checked' : 'unchecked';
Post Reply