I have an html select and a add button. If any one click on add button then an html select create same class, name. My problem is if I change first html select then change function work properly but if I change created html select then change function don’t work. Please can someone point out what I may be doing wrong here? Many thanks. Here is my code:
<html>
<head>
<title>the title</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$(document).on('change','.name',function(){
calculateSum();
});
$(document).on('click','.del',function(){
calculateSum();
});
});
function calculateSum() {
$.post(
"data.php",
$(".name").serialize(),
function(data) {
$('#stage1').html(data);
}
);
}
</script>
<script type="text/javascript" language='javascript'>
/*
This script is identical to the above JavaScript function.
*/
var ct = 1;
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = '<div class="del" style="text-align:right;margin-top:-20px"><a href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
</script>
</head>
<body>
<div id="stage1" style="background-color:blue; color: white">
STAGE - 1
</div>
<form id="testform">
<div id="newlink">
<table>
<tr>
<td><p>Fruit:</p></td>
<td>
<select class="name" name="name[]">
<option>Apple</option>
<option>Mango</option>
<option>Orange</option>
<option>Banana</option>
</select>
</td>
</tr>
</table>
</div>
<input type="button" value="Add" onclick="javascript:new_link()"/>
</form>
<div id="newlinktpl" style="display:none">
<table>
<tr>
<td><p>Fruit:</p></td>
<td>
<select class="name" name="name[]">
<option>Apple</option>
<option>Mango</option>
<option>Orange</option>
<option>Banana</option>
</select>
</td>
</tr>
</table>
</div>
</body>
</html>
php code:
<?php
$fruit=$_REQUEST["name"];
$n = count($fruit);
for($i=0;$i<$n; $i++)
{
echo $fruit[$i]."<br/>";
}
?>
The jQuery FAQ docs have a good description of your situation.
http://docs.jquery.com/Frequently_Asked_Questions#Why_doesn.27t_an_event_work_on_a_new_element_I.27ve_created.3F
You need to use event delegation in order to bind events to future elements that don’t exists when the code is run.
Use
on()method and bind the event to an element that will always exist or to the document itself.API Reference : http://api.jquery.com/on/