This quick tip describes how to have your browser remember the state of checkboxes once a page has been refreshed or a user navigates away from your site to come back at a later date.
[author_more]
It might be useful to Persist Checkbox Checked State if, for example, you use checkboxes to allow your users to set site-specific preferences, such as opening external links in a new window or hiding certain page elements.
For the impatient among you, there's a demo of the technique at the end of the article.
The Checkbox Markup
So, the first thing we'll need are some checkboxes. Here are some I made earlier:
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check All</button>
</div>
You'll notice that I've included a Check All button to allow a user to select or deselect all of the boxes with one click. We'll get to that later.
You'll hopefully also notice that I'm using labels for the text pertaining to each of the boxes. It goes without saying that form fields should have labels anyway, but in the case of checkboxes this is particularly important, as it allows users to select/deselect the box by clicking on the label text.
Finally, you'll see that I'm grouping the labels and check boxes inside block-level elements (<div>
elements in this case), so that they appear beneath each other and are easier to style.
Responding to Change
Now let's bind an event handler to the checkboxes, so that something happens whenever you click them. I'm using jQuery for this tutorial although, of course, this isn't strictly necessary. You can include it via a CDN thus:
<script src="http://ift.tt/1N7dbW8"></script>
Now the JavaScript:
$("#checkbox-container :checkbox").on("change", function(){
alert("The checkbox with the ID '" + this.id + "' changed");
});
Here I'm using jQuery's psuedo-class :checkbox selector, preceded by the ID of the containing <div>
element (checkbox-container
). This allows me to target only those checkboxes I am interested in and not all of the checkboxes on the page.
Persist Checkbox Checked State
As you're probably aware HTTP is a stateless protocol. This means that it treats each request as an independent transaction that is unrelated to any previous request. Consequently if you check a checkbox then refresh the page, the browser has no way of remembering the checkbox's prior state and—in the example above—will render it in its unchecked form (although some browsers will cache the value).
Continue reading %Quick Tip: Persist Checkbox Checked State after Page Reload%
by James Hibbard via SitePoint
No comments:
Post a Comment