Richard
Richard

Reputation: 1464

jquery append() is happening twice

Here's my code so far,

$('label').click(function () {
        if ($('label input').is(':checked')) {
            $(this).addClass('checked');
            $('.donate-now label').not(this).removeClass('checked');

            var donateAmount = $(".checked input").val();
            $('p').append(donateAmount);
        }

    });

I'm checking to make sure the "donateAmount" variable is grabbing only one value, so to test, I'm having it append to the HTML, but it's showing up twice.

Is that a function of append() and my variable only has one value, or is something wrong? Essentially I just want to make sure my variable has one value.

Here it is in action, http://jsfiddle.net/YB8UW/15/

Thank you

Upvotes: 0

Views: 10865

Answers (4)

Imron Rosadi
Imron Rosadi

Reputation: 91

you must try .clone()[0].outerHTML before append to parent element

Upvotes: 0

AlbertEngelB
AlbertEngelB

Reputation: 16436

You should .empty() the container before you append it. :)

http://jsfiddle.net/droppedonjapan/YB8UW/29/

Why your event is being fired twice, I'm not 100% sure, but I think it may be the way the labels' click event goes off. I'm pretty sure it's delegated to your radio input, which then triggers another label click.

I also changed your code a bit to reduce the nesting/ chaining. Let me know if that takes care of it for you!

Upvotes: 0

ncksllvn
ncksllvn

Reputation: 5769

Instead of append, use:

$('p').html(donateAmount);

Append will put a new element in that <p> element everytime, rather than replacing the contents of it.

Upvotes: 2

Tim Withers
Tim Withers

Reputation: 12059

Try changing your selector to:

$('label input').click(function () {
....
});

http://jsfiddle.net/YB8UW/18/

Your problem is that you are clicking the label AND radio when you click on the radio. Since you are clicking the child element, the event fires twice. If you focus the selector in a little more and only capture when the radio button is clicked, it will only fire once. Clicking the label fires a click on the input as well.

Changing it from append to replace doesn't fix the issue, just masks it.

Upvotes: 7

Related Questions