Saving jQuery accordion state on post

Here’s something I picked up by experimentation during the development of a CRUD system, which managed users, inventory, orders and reservations. The question was, how do I have page specific forms to add, update, and delete entries?

The answer was the accordion.

The problem with using the accordion in this way from a usability perspective is it won’t save the tab you were on if you post a form (e.g. if you have an update form in tab 2, where you select an ID from a drop-down box and submit to populate the form fields with the information in the row selected).

“Remembering” the state can be achieved with a PHP statement:

if (!$_POST['update_select
'] && !$_POST['delete_select']) {
?>

This code says if an update or delete id select form hasn’t been posted, initialise the accordion without any tabs active. (active: false).

Right underneath that, add the next conditional statement:

}
if ($_POST[
'update_select']) {
?>

This statement adds a new property, active: 1. This tells the accordion that this tab should be open when the page loads (note: if you’re wondering why it’s 1 instead of 2, it’s because arrays always start at 0).

The last part of the statement handles the delete selector:

}
elseif ($_POST[
'delete_select']) {
?>

This statement does exactly the same as the update_select section, but corresponds to the delete selector. Now simply close off the elseif statement and you’re ready to roll:

}
?>

I hope this tip helps you as much as it helped me!

Photo credit: Crevier via Flickr/Creative Commons

Thank you for your comment. It has been submitted for approval.

Comment Again?

Leave a comment

Please enter your name.
Sorry, this email address is not valid.
Please enter your comment.

Course basket x

Course

Price per place

Add another courseCheckout

Pay now by credit card or later by invoice (invoice payments only possible if all courses are 3+ weeks in advance)