tags:

views:

518

answers:

5

I apply:

$(".newContentLink").click(function() {
    $("#test").append("1");
});

On this:

<span id="contents">
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content1" class="content study">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content3" class="content study">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
<span id="content4" class="content category">
</span>
<input class="newContentLink" type="submit" style="width: 100%;" value="CREATE A NEW CONTENT"/>
</span>

How come when I click on the first 2 buttons it adds 111, the next button adds 11, and the last one adds 1?

A: 

Try giving different names to your submit input elements.

EFraim
I'd like to but they are formed in a loop by my script (I only put what I hope is the relevant part of the code up there).
Eliyahu
I am just concerned it might have something to do with successful control definition.
EFraim
+11  A: 
chaos
Yup, it's almost definitely the `click` handler being added again and again.
Blixt
Or use the .live() method to dynamically add event
MacAnthony
A: 

Not a jQuery bug - Working Demo

There must be a problem with something else in your code. Where is the element with id="test" in your markup?

EDIT:

Just read chaos' answer, which sounds like a plausible explanation.

By the way, element ids must be unique within HTML markup - this is part of the HTML specification and may be another possible explanation

Russ Cam
+3  A: 

As chaos says, you're probably calling click each time you add one, and they're accumulating.

If you're adding these items to the document dynamically, and need to make sure this function is added to every one you add, how about using live?

$(".newContentLink").live().click(function() {
    $("#test").append("1");
});

This will make sure the rule is dynamically applied once to any qualifying class in the document.

Marcus Downing
Whoops, MacAnthony already suggested that.
Marcus Downing
I believe the syntax should be .live( 'click', function () {
MacAnthony
That code didn't work for me. I checked the docs, and this did:$(".newContentLink").live("click", function(){ $("#test").append("1"); });
Eliyahu
I confess, I didn't check the syntax before posting.
Marcus Downing
A: 

I had a similar problem.... Figured out that i was applying the change function in a loop...i.e. my earlier code was....

$("table#UserIRTable > tbody > tr").each(function()
{
..............
..............

$("input[id='thisMonthSupply']").change(function(e){ ...... });
..........
..........
}

took the change function out and bingo... it worked.....

Prabhjot Singh Lamba