Jquery live, make your html “go live”

21 Jun

Jquery .live()

Description: Attach a handler to the event for all elements which match the current selector, now and in the future.

I want to show you how to make the default input value, adding the dom elements and using jquery live function, all blended together. Click add button to add more input value with default value included. Default text will disapper if focus in and reappear if focus out.

First, create the html

<div id="contentPan">
Hardcopy: <br>
<input name="hardcopy[]" size="50" type="text" value="Default text">
<a href="#" id="button-add-hardcopy">
<img src="add.png" border="0">
</a> <br>
<div id="add-hardcopy"></div>

Link your jquery and css files

<link href="div.css" rel="stylesheet" type="text/css">
<script src="jquery-1.6.1.js" type="text/javascript"></script>

Then, create the jquery code

<script type="text/javascript">
// Var
base_img = '';


// Default input value
function() {
if ($(this).val() == 'Default text') {
function() {
if ($(this).val() == '') {
$(this).val('Default text');

// Html dom added
$("#button-add-hardcopy").click(function() {
var defVal    = $(this).prev('input.hardcopy').val();
var input     = '<span style="display:none"><input value="'+defVal+'" type="text" name="hardcopy[]" size="50" /> <a href="#"><img border="0" src="'+base_img+'delete.png" /></a></span>';


//bind element with event function
$(".button-delete-hardcopy").click(function() {
$(this).parent().empty().fadeOut('slow', function() {

And the last, create the css file

background: url("input_background.png") repeat-x scroll left top #FFFFFF;
border: 1px solid #CCCCCC;
border-radius: 3px 3px 3px 3px;
font-family: Arial;
font-size: 11px;
padding: 3px;

.span-add-hardcopy {
margin-top: 5px;

position: relative;
width: 400px;
background-color: #ccc;
padding: 20px;

Browser compatibility check including:

  • firefox 4.0.1
  • safari 5.0.2
  • chrome 12.0.742.100
  • ie 9

Full example can be download here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: