user123456789 user123456789 - 3 years ago 85
jQuery Question

Jquery toggle between append and remove not working as i expected

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>


Working Demo Here..

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

Answer Source

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download