Showing posts with label changer. Show all posts
Showing posts with label changer. Show all posts

Friday, 12 July 2013

Form changer jQuery plugin

Websites I work on often include the need to add a login, password reset and self-registration form. This requirement can either take up too much space on the page, or require a refresh to load each form. They could all easily be put in a container like a div and called upon (or shown) only when needed. This is what I've done with the example below.
The 'data-location' anchor attributes must correspond to the form ID's they are requesting.
First, I've hidden all the things not required to be visible on load and just spaced the links out (in blue).
Second, I've created the container, forms and links I need (in red).
Third, I've called my plugin to handle the interaction (in green).
Below the HTML, I present the plugin code. There is a little catch all at the top, just in case anyone creates a container with either an ID, class or neither.
<!DOCTYPE html>
<html lang="en">
<title>Form changer</title>
#formholder #resetpassword, #formholder #selfregister, #formholder a[data-location="login"]
#formholder a
<script src=""></script>
google.load("jquery", "1");
<div id="formholder">
<form id="login">
<p>Hello from login</p>
<form id="resetpassword">
<p>Hello from reset password</p>
<form id="selfregister">
<p>Hello from self-register</p>
<a href="#" data-location="login">Login</a><a href="#" data-location="resetpassword">Reset password</a><a href="#" data-location="selfregister">Self-register</a>
<script src="formchanger.plugin.js"></script>
$('#formholder a').formchanger();

Now the plugin code:
$.fn.formchanger = function()
id = $(this).parent().attr('id');
clas = $(this).parent().attr('class');
tag = $(this).parent().get(0).tagName;
if(id != null)
container = '#'+id;
else if(clas != null)
container = '.'+clas;
container = tag;
anchors = $(container).children('a');
forms = $(container).children('form');
$(container+' #'+$(this).data('location')).show();