12

Hi all i have a contact form and captcha is there. i want keep the check is checked after submitting the form. I posted the textbox values and it showing correctly but checkbox is not working. here is my code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org /TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form action = "" name="frmSubmit" method="post">
<input type="checkbox" name="txtCheck" value="<?php echo $_POST['txtCheck'];?>"  /><br />
<label>Name</label><br />
<input type="text" name="txtName" id="NameTextBox" value="<?php echo $_POST['txtName']; ?>" />
<br />
<label>E Mail</label><br />
 <input type="text" name="txtEmail" id="EmailTextBox" value="<?php  echo $_POST['txtEmail'];?>" />
 <input name="BtnSubmit" type="submit" onclick="MM_validateForm('NameTextBox','','R','EmailTextBox','','R');return document.MM_returnValue" value="Send" />
</form>
</body>
</html>

How to keep check box after submitting the form.?

5 Answers 5

27

change

<input type="checkbox" name="txtCheck" value="<?php echo $_POST['txtCheck'];?>"  /><br />

to

<input type="checkbox" name="txtCheck" value="your value" <?php if(isset($_POST['txtCheck'])) echo "checked='checked'"; ?>  /><br />

this will keep checkbox checked..

Sign up to request clarification or add additional context in comments.

3 Comments

What if the checkbox is within an array? name="txtCheck[]"
<?php if (in_array("your_value", $_POST['txtCheck'])) echo "checked='checked'"; ?>
thanks what happens if i do not want to keep all of them selected in the array. only the one that were selected
1

If the submitted value is not empty, then add the checked="checked" attribute to the checkbox:

<input type="checkbox" name="txtCheck" value="1" <?php if (!empty($_POST['txtCheck'])): ?> checked="checked"<?php endif; ?> />

You can however leave the value attribute intact.

Comments

0
<input type="checkbox" name="txtCheck" <?php if($_POST['txtCheck']>0){ ?>checked="checked" <? }?> />

Comments

0

Try this:

$checked = "";
if ($_POST['txtCheck']) {
  $checked = "checked";
  // May need to be "checked='checked'" for xhtml
}
<input type="checkbox" name="txtCheck" <?php echo $checked;?>  /><br />

Comments

0

By apply ternary condition in checkbox tag field we can set whether this is checked or not on form submission

<input type="checkbox" value="1" name="nofollow" <?=isset($_POST['nofollow'])?"checked":''; ?> >

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.