Keep checkbox checked after form submit in Codeigniter

The set_value('field name') function in codeigniter allows us to retain the value of input field in form during form submission but it’s not applicable to keep checkbox checked if it was checked while the form was submitted or during postback submit refresh. Here to keep checkbox checked after form submit in Codeigniter, the set_checkbox() function plays the role.

In this article I’m describing how can you use set_checkbox() function to retain checkboxes checked after pressing submit button? After understanding the concept you will be able to use similar functions set_select() and set_radio() available in Codeigniter to retain status of dropdowns and radio buttons as well.

Keep checkbox checked after form submit in Codeigniter

So at first we have a regular checkbox in our form. Let’s say it’s an ‘Accept TOS‘ checkbox as given:

 If you check to checkbox submit the form and form validation gets fail due to some reason then the form will loss the check status of the checkbox. To preserve the status of ‘Accept TOS‘ in our example, we can modify the markup with a little php code as following:

The set_checkbox() permits you to display a checkbox in the state it was submitted and accepts three parameters:

  • $field (string | required) – Name of the checkbox field to check. ‘accept_terms_checkbox‘ in our case. 
  • $value (string | required) – Value to check for. ‘Accept TOS‘ in our case.
  • $default ( boolean | optional)TRUE or FALSE, by default FALSE to keep checkbox unchecked initially.

So the function checks value with field name supplied to it and places ‘checked=”checked”‘ if the checkbox status is checked during form submits. Also there is a third parameter which keeps the checkbox checked initially if set to true.

It’s all the concept and explanation behind keep checkbox checked after form submit in Codeigniter and hope it helped you to understand the function and process behind it. Don’t forget to read Form Validation rule to validate checkbox to easily validate checkboxes or radio buttons in a Codeigniter form.

Like this Post? Share