Ajezior
Ajezior

Reputation: 72

PHP form checkbox always returning value

Even when the checkbox is unselected it is still returning the Value. I am passing the form through an Ajax request and printing the returned value, but it is the same result checked or unchecked. Isset not working properly either.

<input type="checkbox" value="Agree" id="siteAgreement">

if(!isset($siteAgreement) || !$siteAgreement || $siteAgreement != "Agree"){
//////Unchecked
}

Upvotes: 1

Views: 1922

Answers (4)

Jan Tojnar
Jan Tojnar

Reputation: 5524

Change

siteAgreement = $("#siteAgreement").value;

to something like this:

siteAgreement = $("#siteAgreement").is(':checked') ? $("#siteAgreement").val() : null;

But you should also add the name attribute so browsers with javascript turned off can also use your site.

Also you can use some code that generates request automatically from form (something like jquery.form), so you don't have to update javascript whenever you change the form.

Example here: http://jsfiddle.net/RhasK/

Upvotes: 3

Boundless
Boundless

Reputation: 2464

you should only need to check if it is set or not.

if(!isset($_POST['siteAgreement'])){
//then it is unchecked
}

Also, you didn't give your input a name. You need to put...

<input type="checkbox" name="siteAgreement" value="Agree" id="siteAgreement">

You need a name to access it in PHP.

Upvotes: 0

Stefan
Stefan

Reputation: 2194

if($_POST["siteAgreement"] !== "Agree") {
//not checked
}

will work fine

Upvotes: 0

user1909426
user1909426

Reputation: 1668

Here try this:

 if(!isset($_POST['siteAgreement']) || !$_POST['siteAgreement'] || $_POST['siteAgreement'] != "Agree"){
 //////Unchecked
 }

Unless you're extracting the variable before, $siteAgreement won't be set. You can use $_POST['nameofelement'] to access the data.

Upvotes: 0

Related Questions