jQuery+cookies = trivially simple form autofill
Posted Fri, 30 Jun 2006
It's always nice when websites you commonly visit remember things about you, or
atleast give the perception that they remember things about you.
The Pyblosxom comment plugin doesn't autofill the form. That's too bad. I don't really want to dig into the python code to do any cookie-setting on submission, becuase I have never looked at the code and thusly am unfamiliar with the effort required for such a change. Luckily, we can use javascript to store data in cookies too!
I love jQuery, so that's what I'll use for this little hack. On the comments page, I add the following javascript:
var uname = "u.name";
var uemail = "u.email";
var usite = "u.site";
function saveCommentInformation() {
// Save user information from the form!
createCookie(uname, $("input[@name='author']").val());
createCookie(uemail, $("input[@name='email']").val());
createCookie(usite, $("input[@name='url']").val());
}
function initCommentForm() {
// Autofill user information if available
$("input[@name='author']").val(readCookie(uname));
$("input[@name='email']").val(readCookie(uemail));
$("input[@name='url']").val(readCookie(usite));
// Save comment information when form is submitted
$("form[@name='comments_form']").submit(saveCommentInformation);
}
$(document).ready(initCommentForm);
That's all we need. Whenever someone submits, we will store useful information in a cookie. Whenever that person comes back, we'll pull the data out of the cookie and put it back in the form. User Experience is happier, atleast as far as I am concerned (as a user).
If you are wondering about the 'readCookie' and 'createCookie' functions, you can find them on quirksmode.org:
http://www.quirksmode.org/js/cookies.html
Update: Check out this followup post that implements this in a more jquery-like way.
Thank you, Jordan for this article!