tags:

views:

26

answers:

2

Hello,

Please find the code below

<script type="text/javascript">
    $(function(){
    var c=1;
        $("#i1").toggle(function(){
            $("#e1").appendTo("#i2");
            $('#counter').attr('value',c);

        },
        function(){
            $("#e1").appendTo($(this));
           $('#counter').attr('value',c);
        });
    c++; 
    });
    </script>
    <div id=i1><span id="e1">Item 1</span></div>
    <div id=i2><span id="e2">Item 2</span></div>

    <input type=text value='' id=counter>

When the counter is placed, it does increment and decrement, but the value goes up by +2 each time I click on add, and -1 on remove.

What exactly is wrong

Thanks Jean

A: 

show us the page with the code in it. oops, should have been a comment.

Grumpy
The code above is as its on the page
Jean
+1  A: 

I don't realy understand your code. Are there parts missing?

But I think it's because, the c++ will be called only once, when the document.ready runs. and 1+1 = 2, so c will always be 2.

So maybe thats why it always increment with 2.

But I think when

 $('#counter').attr('value',c);

is called, it will always be 2... and not added with 2.

If i use a counter for appending items, is use a hidden field, and would do something like this:

$("#i1").toggle(function(){
    var c= $("#counter").val();
    c++;
    $("#counter").val(c);
    $("#e1").appendTo("#i2");
    $('#counter').attr('value',c);
},
function(){
    var c= $("#counter").val();
    c++;
    $("#counter").val(c);
    $("#e1").appendTo($(this));
    $('#counter').attr('value',c);
});

I hope this was useful.

bruno
At the second function it must decrement
Jean
then c-- instead of c++ (in my piece of code...)
bruno
did that with the same resultI just cannot find out why it is being incremented
Jean