Skip to content

Instantly share code, notes, and snippets.

@micahyoung
Created May 6, 2011 21:56
Show Gist options
  • Save micahyoung/959872 to your computer and use it in GitHub Desktop.
Save micahyoung/959872 to your computer and use it in GitHub Desktop.
jQuery Form Demo
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
ul#current_emails {
list-style: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(){
//selector shortcuts
$form = $('#email_form');
$email_list = $('ul#current_emails');
$add = $('#add');
$delete = $('.delete');
$new_email = $('input#new_email');
//focus on new email field
$new_email.focus();
//clicking the add button creates a new list element from email field
$add.click(function(evt){
evt.preventDefault(); //prevent form submission
email = $new_email.val();
//create new elements
$li = $('<li></li>');
$button = $('<button class="delete">X</button>');
$input = $('<input name="email" type="hidden">');
$span = $('<span></span>');
//setup values
$span.text(email);
$input.val(email);
//attach elements
$li.append($button).append($input).append($span);
$li.appendTo( $email_list );
});
//use live so new delete buttons will get function
$delete.live('click', function(evt){
evt.preventDefault(); //prevent form submission
//get the target button's parent
$button = $(evt.target);
$li = $button.parent();
$li.remove();
});
});
})(jQuery);
</script>
</head>
<body>
<!-- method set to "get" just for debugging -->
<form id="email_form" method="get">
<!-- input for new emails. Has no name so it won't be submitted -->
<input id="new_email" type="text" />
<button id="add">Add</button>
<ul id="current_emails">
<!-- example list item that would be created by jquery -->
<li>
<button class="delete">X</button>
<input name="email" value="test@test.com" type="hidden">
<span>test@test.com</span>
</li>
</ul>
<input type="submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment