Creating HTML elements dynamically using jquery

sometime during your project you need to create some html elements dynamically based on user’s choice.

for example you are providing upload facilities to user such that initially only one upload widget is available but if user want to upload more things, they will click on add button and based on that upload widgets should created and appear there.

so you need to use two methods of jquery.

  • live method
  • clone method

1) live method:

The live() method attaches one or more event handlers for selected elements, and specifies a function to run when the events occur.

Event handlers attached using the live() method will work for both current and FUTURE elements matching the selector (like a new element created by a script).

2) clone method:

The clone() method makes a copy of selected elements, including child nodes, text and attributes.

now let’s write code for creating dynamic elements.

 

<!DOCTYPE html>
<html>
<head>
<script src=”jquery.js”></script>
<script>
$(function()
{
$(‘.Add’).live(‘click’,function(e)
{
$(‘.Option:last’).after($(‘.Option:first’).clone());
});
});

</script>
</head>
<body>
<div class=’Option’><input type=’text’ name=’t1′/>
<span class=’Add’><img src=”add.png” height=”30″ width=”30″/></span>
</body>
</html>

dynamically_element

if you press add button you will get another same row of textbox and add button.!

hope you like it.!

Advertisements

2 thoughts on “Creating HTML elements dynamically using jquery

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s