Page 1 of 1

checkbox value problem in $_POST

Posted: Sun Mar 14, 2010 8:50 pm
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?

Re: checkbox value problem in $_POST

Posted: Tue Mar 16, 2010 4:15 pm
by Sofw_Arch_Dev
This is how HTML forms work. Checkbox values are only sent if the checkbox is CHECKED.

Re: checkbox value problem in $_POST

Posted: Tue Mar 16, 2010 6:17 pm
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

Re: checkbox value problem in $_POST

Posted: Thu Mar 18, 2010 4:47 pm
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);
 
    }

Re: checkbox value problem in $_POST

Posted: Thu Mar 18, 2010 4:50 pm
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';