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?
Try giving different names to your submit input elements.
To make sure the function only execute once on one click event you may use $(".newContentLink").one();
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?
This will make sure the rule is dynamically applied once to any qualifying class in the document.
or you can unbind the click event each time you add a new element
Unable to replicate. I suspect that you're misrepresenting — oversimplifying, mostly — your situation. To be precise, I believe you're dynamically adding those inputs, and calling
$(".newContentLink").click(...)
each time — which, naturally, keeps applying additional copies of the click handler to each.newContentLink
in the page.So the most recent input you've created has one copy of the click handler and appends one
1
. The second most recent has two copies and appends11
. The third has three and appends111
, etc.To prevent this, apply the click handler to your newly created DOM element, not
$(".newContentLink")
(which always means every.newContentLink
).I had a similar problem.... Figured out that I was applying the change function in a loop...i.e. my earlier code was....
took the change function out and bingo... it worked.....