You need to use event Delegation
Change
$('.m').on('click',function()
to
$(document).on('click', '.m', function()
And it's a bad practice to use inline events. You always have an option of attaching events in javascript..
Also the way you were binding events binds the events multiple times for each checkbox in the table. That is because , whenever you click on a checkbox, you call the function n()
. This selects all the elements with class="m"
and attaches the events on them.
The way you were supposed to handle that was passing the this
context to the function and completely remove the event handling signature from inside the function.
You code should look like below.
$(document).on('click', '.m',function() {
var id = $(this).closest("tr").find(".t").text();
var p= $(this).closest("tr").find(".t1").text();
$('#c').append('<span>', id, '</span>');
});
for(int i=0;i<10;i++) {
div.innerHTML="<table><tr><td><input type='checkbox' class='m'></td>"
+ "<td class='m'>data</td><td class='t1'>data</td></tr></table>";
}
//appending values on checkbox selection
<div id='c'></div>
UPDATE
You have incorrect closing tags and the structure has many syntax errors. Also remove the function n()
which is called from onclick=n()
as you are already binding the event in javascript. Your code should look like below
<style>
.c:hover { color:red; };
.li { };
</style>
<script>
// document Ready handler
$(function () {
// Click event for elements with class m
$(document).on('click', '.m', function () {
var id = $(this).closest("tr").find(".t").text();
var p = $(this).closest("tr").find(".t1").text();
$('#c').append('<li class="li">id<span class ="c">X</span></li >');
});
// Click events for elemenst with class c
$(document).on('click', '.c ', function () {
$(this).closest("li").remove() alert("ok");
});
});
</script>
This line
$('#c').append('<li class="li">id<span class ="c">X</span></li >');
supposed to be
$('#c').append('<li class="li">'+ id + '<span class ="c">X</span></li >');
And
$('#cart1').append('<span id=li1>',id,+p,+q ,"Amount="+p*q,'<span class=close>X</span></span>','</br>');
Supposed to be
$('#cart1').append('<span id="li1">' + id + p + q + 'Amount=' + (p * q) + '<span class=close>X</span></span></br>');