Jump to content
HenryCan

Turn checkboxes on or off programatically

Recommended Posts

Posted (edited)

How do I turn a checkbox on or off programatically?

My form has several checkboxes that are grouped together and I want them to be turned on initially when the user first sees the form.I can do that very easily by just including "checked" in the HTML for the checkbox. But if the user turns off the checkbox before he presses Submit, I want to make sure I show the ones that are off as off when I redisplay the form as a result of errors in other fields, like textareas.

How do I turn the checkbox off or on within my PHP code?

Edited by HenryCan

Share this post


Link to post
Share on other sites

I'm not sure why you're asking this: you already know how to make checkboxes marked through the "checked" attribute... If you don't want them to be checked then, you know, don't use the attribute.

Share this post


Link to post
Share on other sites

assuming that you are dynamically producing the checkboxes (if not that would be your 1st step), you would test if the corresponding submitted post data isset() for the current checkbox you are outputting. to address that you are initially checking all the checkboxes, you would have a common program variable that you initially setup with the necessary data, then copy the submitted post data to the same variable once the form has been submitted. see the following example code -

<?php

// recursive trim call-back function
function _trim($val)
{
	if(is_array($val))
	{
		return array_map('_trim',$val);
	} else {
		return trim($val);
	}
}

$post = []; // holds a trimmed, working copy, of the submitted post data or any initial data

// post method form processing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
	// examine the submitted data
	echo '<pre>'; print_r($_POST); echo '</pre>';

	$post = array_map('_trim',$_POST); // get a trimmed copy of the submitted post data. use elements in $post in the rest of the code on the page
	
	// the rest of the form processing code goes here...
	
}


// get method business logic - get/produce data needed to display the page
// if you were editing existing stored data, you would initially (if the $post variable is empty) retrieve that here into the $post variable
if(empty($post)) // note: this requires at least one non-checkbox/radio form field to be present in case all checkbox/radio fields are ever unchecked
{
	// for a set of defined checkboxes that are initially set, the same as through you were editing existing data where all the checkboxes are initially checked, set that up here
	// loop over a 'defined' list of checkboxes. for demo purposes this is just a list of ids from 1-4
	foreach(range(1,4) as $id)
	{
		$post['chk'][$id] = true;
	}
}
?>

<form method='post'>
<input type='hidden' name='action' value='create'>
<?php
// loop over a 'defined' list of checkboxes. for demo purposes this is just a list of ids from 1-4
foreach(range(1,4) as $id)
{
	// determine if checkbox is checked
	$chk = isset($post['chk'][$id]) ? ' checked' : '';
	echo "<input type='checkbox' name='chk[$id]'$chk> Checkbox: $id<br>";
}
?>
<input type='submit'></form>

 

  • Like 1

Share this post


Link to post
Share on other sites
Posted (edited)
8 hours ago, requinix said:

I'm not sure why you're asking this: you already know how to make checkboxes marked through the "checked" attribute... If you don't want them to be checked then, you know, don't use the attribute.

I want the checkboxes to be INITIALLY checked but if the user unchecks some of them before pressing Submit and then I have to redisplay the form to show error messages in other fields, I need to display the ones he unchecked as unchecked when I display the errors.

If I just hard-code "checked" in the checkbox description, I don't see how I'm going to uncheck them programmatically and keep them unchecked on the form.

Edited by HenryCan

Share this post


Link to post
Share on other sites

When you receive the form the first time (and every time after that) create an array of the 'values' that were checked.  When you output the form again, as you build the html code check that array for the values that need to be re-checked and check them as they are built.

easy-peasy.

  • Like 1

Share this post


Link to post
Share on other sites

Thank you, mac_gyver and ginerjm. I imitated the approach you suggested and everything is working fine now.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.