Create a sample form with button which used to create dynamic select tag and dynamic event binding
Here i am using the select tag for my test to bind the event dynamically. we are created a sample form that form contains one button for creating a dynamic select tag. We are going to write a change event for that dynamically created select tag.
The following code may explain how can i write a events for dynamically created elements in html using JQuery. For that we need jquery.
Source Code:
<html>
<head>
<script src="jquery-1.6.js" type="text/javascript"></script>
<script>
var n=1;
$(document).ready(function(){
$("#createselect").click(function(){
var newelement=$(document.createElement('div')).attr('id','test'+n);
newelement.html('<label>select tag'+n+'</label><select id="selectid'+n+'" class="dynamicallycreated" ><option>option1</option><option>option2</option><option>option3</option></select>');
newelement.appendTo("#testing");
n++
});
$('select.dynamicallycreated').live('change',function(){
$(this).next('p').empty();
$(this).after("<p>"+$(this).val()+" is selected</p>");
});
});
</script>
</head>
<body>
<div id="testing">
</div>
<input type="button" id="createselect" value="create">
</body>
</html>
This code is for creating any number of select tag and bind the change method for each element in dynamically. For that i used the live method also take class name as a selector of my test.
Comments
Post a Comment