PHPLover
PHPLover

Reputation: 12957

How to access two different values for one checkbox?

I'm using HTML, PHP, jQuery for my website. I've a check box on my form as follows:

<input type="checkbox" name="check_status" id="check_status" value="1"> Status

I want the same check box for two different values. In short, after submission of the form if check box is checked I should get the value 1 in $_POST['check_status'] array and if the check box is unchecked at the time of submission of form I should get the value as 0 in $_POST['check_status'] array after form submission.

Now as per the above HTML code if check box is checked I'm getting value 1 and if the check box is unchecked then I'm getting blank value.

How should I resolve this issue to achieve the desired result?

Upvotes: 0

Views: 971

Answers (3)

Daniel
Daniel

Reputation: 1861

In case you really need those values to be send as 1 and 0 to the server ( maybe you can't change the server-side code), you can add a hidden field with the same name as your checkbox, and then use JavaScript/jQuery to fill that hidden field, before you submit the form, with 1 or 0, for checkbox being checked, respectively unchecked. .

$("#hiddenField").val( $('#checkbox').is(':checked') ? 1 : 0 );

Upvotes: 0

Satish Sharma
Satish Sharma

Reputation: 9635

you can use this

$status = 0;
if(isset($_POST['check_status'])) {
    $status = 1;
}

echo $status;

Upvotes: 1

TBI
TBI

Reputation: 2809

You can add condition in php. Hope this will help.

if(isset($_POST['check_status'])) {
    $status = $_POST['check_status'];
} else {
    $status = 0;
}

echo $status;

Upvotes: 3

Related Questions