Reputation: 566
The following toggle between append and remove does not work:
$('.t').click(function() {
var className = $(this).data('class');
$(this).toggleClass(className).toggleClass(className+'1');
var newTable='<table style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>';
$("#newDiv").append(newTable).remove(newTable);
});
HTML
<div class="t a" data-class="a"> 8cghfghfghfghfg</div>
<div class="t b" data-class="b">20cghfghfghfghfg</div>
<div class="t c" data-class="c"> 4cghfghfghfghfg</div>
<div id="newDiv"></div>
Here, what i want to do is.. if i click on div.t, i want to remove the particular class(Ex: .a) and add respective class (Ex .a1), this one i achieved.
But i want to add a table while clicking first time, want to remove that added table while second time clicking.
how can i achieve this, please can anyone help me put...
Thanks
Upvotes: 2
Views: 5752
Reputation: 11381
To toggle append and remove, you can make use of the data
property of the clicked element. Its a cleaner approach :
$('.t').click(function () {
//general stuff must happen everytime class is clicked
//get the className from data- attr
var className = $(this).data('class');
//toggling to change color
$(this).toggleClass(className).toggleClass(className + '1');
//check if its clicked already using data- attribute
if ($(this).data("clicked")) {
//remove it if yes
$("#newDiv").find("#tablefor-" + className).remove();
} else {
//new table - note that I've added an id to it indicate where it came from
var newTable = '<table id="tablefor-' + className + '" style="font-size: 14;float:left;padding-left: 13px;" cellpadding="5"><tr><td style="color: #B2B2B9;">T1' + className + '</td></tr><tr><td id="cap">20</td></tr><tr><td id="minseat">8</td></tr></table>';
//append table
$("#newDiv").append(newTable);
}
//reverse the data of clicked
$(this).data("clicked", !$(this).data("clicked"));
});
Demo : http://jsfiddle.net/hungerpain/m9ak9/11/
Upvotes: 4
Reputation: 3183
Just use an if
switch to determine wether the table is already present or not. I modified your fiddle to demonstrate this: http://jsfiddle.net/m9ak9/6/
I added an id
to the table to make it easiert to identify, but you could also look for it with something like this:
var findTableInDiv = $('#newDiv').find('table');
Upvotes: 0